码迷,mamicode.com
首页 > 其他好文 > 详细

1.rest-framework学习

时间:2018-12-05 02:18:12      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:erro   cad   serialize   lse   err   sel   source   class   tle   

新建三张表

 1 class Author(models.Model):
 2     name=models.CharField(max_length=200)
 3     def __str__(self):
 4         return self.name
 5 
 6 class Publish(models.Model):
 7     name = models.CharField(max_length=200)
 8     def __str__(self):
 9         return self.name
10 
11 class Book(models.Model):
12     title=models.CharField(max_length=200,verbose_name=题目)
13     author=models.ManyToManyField(Author)
14     publish=models.ForeignKey(Publish,on_delete=models.CASCADE)
15     def __str__(self):
16         return self.title

拿book表来说,序列化

1 class Bookserialize(serializers.ModelSerializer):
2     class Meta:
3         model=Book
4         fields="__all__"
5     def create(self, validated_data):
6         print(va,validated_data)
7         author=validated_data.pop(author)
8         obj=Book.objects.create(**validated_data)
9         obj.author.add(*author)

不重写create也可以,只是为了学习,还可以序列化超链接

    title=serializers.CharField(max_length=200)
    author=serializers.SerializerMethodField()
    publish=serializers.CharField(source=publish.name)
    publish = serializers.HyperlinkedIdentityField(
        view_name=publish_detial,
        lookup_url_kwarg=id
    )

    def get_author(self,obj):
        s=[]
        for o in obj.author.all():
            s.append(o.name)
        return s

view视图,如果用了序列化超链接,记得加上context

 1 class Bookview(APIView):
 2     def get(self,request):
 3         booklist=Book.objects.all()
 4         bs=Bookserialize(booklist,context={request: request},many=True)
 5         return Response(bs.data)
 6 
 7     def post(self,request):
 8         print(request.data)
 9         bs=Bookserialize(data=request.data,many=False)
10         if bs.is_valid():
11             bs.save()
12             return Response(bs.data)
13         else:
14             return JsonResponse(bs.errors)
15 
16 class BookDetial(APIView):
17     def get(self,request,id):
18         book=Book.objects.filter(id=id).first()
19         bs=Bookserialize(book,context={request: request},many=False)
20         return Response(bs.data)
21     def put(self,request,id):
22         book = Book.objects.filter(id=id).first()
23         bs=Bookserialize(book,data=request.data)
24         if bs.is_valid():
25             bs.save()
26             return Response(bs.data)
27     def delete(self,request,id):
28         book=Book.objects.filter(id=id).first()
29         book.delete()
30         return Response()

get方法里传入数据不用data

post需要data

put里的data接受request.data

一对多:source 使用模型名.字段

多对多:get_模型名  author=serializers.SerializerMethodField()

 

1.rest-framework学习

标签:erro   cad   serialize   lse   err   sel   source   class   tle   

原文地址:https://www.cnblogs.com/losenine/p/10068462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!