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

DRF一对多序列化和反序列化

时间:2019-10-22 23:56:54      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:添加   名称   api   http   att   ons   _id   put   pre   

DRF一对多序列化和反序列化

  • models.py

    # 商品分类
    class Category(models.Model):
        name = models.CharField(max_length=32)
    
    # 商品
    class Goods(models.Model):
        name = models.CharField(max_length=32)
        price = models.DecimalField(max_digits=9,decimal_places=2)
        cate = models.ForeignKey(to='Category',on_delete=models.CASCADE)
  • urls.py

    from django.urls import path,include
    from . import views
    urlpatterns = [
        path('goods/',views.GoodsView.as_view()),
    ]
  • seralizers.py

    # 序列化
    class GoodsSerializer(serializers.ModelSerializer):
        # 如果想查出分类名称 CharField(source='<本model中的外键>.<外键指向的model的相应属性>')
        cate_name = serializers.CharField(source='cate.name')
        class Meta:
            model=Goods
            fields = ('cate_name','name','price')
    
    # 反序列化
    class GoodsUnSerializer(serializers.Serializer):
        name = serializers.CharField(max_length=32)
        price = serializers.DecimalField(max_digits=9,decimal_places=2)
        cate = serializers.IntegerField()
    
        # 添加
        def create(self, data):
            return Goods.objects.create(
                cate_id = data.pop('cate'),
                **data
            )
        # 编辑
        def update(self,instance,data):
            return instance.update(
              cate_id = data.pop('cate'),
                **data
            )
    
  • views.py

    class GoodsView(APIView):
      # 查询
        def get(self,request):
            goods = models.Goods.objects.all()
            gs = GoodsSerializer(goods,many=True)
            return Response(gs.data)
    
      # 添加
        def post(self,request):
            dic = {"name":"金丝猴","price":132,'cate':3}
            gs = GoodsUnSerializer(data=dic)
            if gs.is_valid():
                gs.save()
                return HttpResponse('ok')
            return HttpResponse('error')
    
        # 更新
        def put(self,request):
            obj = models.Goods.objects.filter(id=1)
            dic = {"name":"金丝猴123","price":234,'cate':2}
            gs = GoodsUnSerializer(obj,data=dic)
            if gs.is_valid():
                gs.save()
                return HttpResponse('put-ok')
            return HttpResponse('put-error')

DRF一对多序列化和反序列化

标签:添加   名称   api   http   att   ons   _id   put   pre   

原文地址:https://www.cnblogs.com/wuxiaoshi/p/11723209.html

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