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

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')
相关文章
相关标签/搜索