完整实例
项目结构 Floral Floral accounts manage.pyFloral/urls.pyfrom django.conf.urls import url, includefrom rest_framework import routersfrom accounts import viewsrouter = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'groups', views.GroupViewSet)router.register(r'ips', views.IpViewSet)router.register(r'comments', views.CommentViewSet)Floral/accounts/models.pyfrom django.db import models# Create your models here.from django.contrib.auth.models import AbstractBaseUserfrom rest_framework import serializersfrom django.utils.translation import ugettext_lazy as _class MyUsers(models.Model): #REQUIRED_FIELDS = ('name',) #USERNAME_FIELD = ('name') groups = models.ForeignKey( 'Groups', null=False, blank=False, related_name='myusers', on_delete=models.CASCADE ) name = models.CharField( null=False, blank=False, max_length=125, ) email = models.EmailField( null=False, blank=False, max_length=125, ) url = models.URLField( null=False, blank=True, max_length=125, )class Groups(models.Model): name = models.CharField( null=False, blank=False, max_length=125, ) url = models.URLField( null=False, blank=True, max_length=125, )class Ip(models.Model): user = models.ForeignKey( 'MyUsers', null=False, blank=False, related_name='ips', on_delete=models.CASCADE ) group = models.ForeignKey( 'Groups', null=False, blank=True, related_name='ips', on_delete=models.CASCADE ) ip_addr = models.GenericIPAddressField( blank=False, null=False, )class Comment(models.Model): email = models.EmailField( null=False, blank=False, max_length=125, ) content = models.CharField( null=False, blank=False, max_length=200, ) created = models.DateTimeField( help_text=_('date'), auto_now_add=True ) user = models.ForeignKey( 'MyUsers', null=False, blank=False, related_name='comments', on_delete=models.CASCADE )Floral/accounts/views.pyfrom django.shortcuts import render# Create your views here.from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom accounts.serializers import UserSerializer, GroupSerializer, IpSerializer, CommentSerializerfrom rest_framework.authtoken.models import Tokenfrom rest_framework.response import Responsefrom knox.auth import TokenAuthenticationfrom knox.models import AuthTokenfrom rest_framework.permissions import IsAuthenticated, AllowAnyfrom accounts.models import Ip, Commentclass GroupViewSet(viewsets.ModelViewSet): """ 允许组查看或编辑的API路径。 """ queryset = Group.objects.all() serializer_class = GroupSerializerclass IpViewSet(viewsets.ModelViewSet): """ 允许组查看或编辑的API路径。 """ queryset = Ip.objects.all() serializer_class = IpSerializerclass CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializerFloral/accounts/serializers.pyfrom django.contrib.auth.models import User, Groupfrom rest_framework import serializersfrom accounts.models import Ipfrom rest_framework.response import Responsefrom datetime import datetimefrom rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParserfrom django.utils.six import BytesIOclass UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups', 'user')class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name')class IpSerializer(serializers.HyperlinkedModelSerializer): #SerializerMethodField(): Serialization and deserialization group = serializers.SerializerMethodField() user = serializers.SerializerMethodField() class Meta: model = Ip fields = ('user', 'ip_addr', 'group') def get_group(self, obj): group = obj.group return{ 'url': group.url, 'name': group.name, } def get_user(self, obj): user = obj.user if user: print(1) return { 'name': user.name + ' ' + 'hello' } def get_attribute(self, instance): a = instance print(a) return instanceclass Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now()class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def create(self, validated_data): return Comment(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) return instancecomment = Comment('1111@qq.com', content='foo bar')serializer = CommentSerializer(comment)s = serializer.datajson = JSONRenderer().render(s)stream = BytesIO(json)data = JSONParser().parse(stream)print(data)serializer = CommentSerializer(data=data)serializer.is_valid()k = serializer.validated_dataprint(k)复制代码
访问http://127.0.0.1:8000/comments/1/
PATCH http://127.0.0.1:8000/comments/1/ 更新部分数据(可以是单条数据) 对应于drf中的update方法
具体的HTTP方法和drff中的操作对应关系参考https://www.jianshu.com/p/69bdfc531f48
使用postman测结果
https://note.youdao.com/yws/res/32204/WEBRESOURCE57124744967a96fa0af039a2aff731a3
如果Comment是一个模型Model
def create(self, validated_data): return Comment(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) return instance可以更改为 def create(self, validated_data): return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance如果你的对象实例对应Django的模型,你还需要确保这些方法将对象保存到数据库。例如,如果Comment是一个Django模型的话。【Django rest framework 官方文档解释】复制代码