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

Posted wuxiaoshi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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')

以上是关于DRF一对多序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章

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

DRF单表序列化和反序列化

drf的序列化和反序列化

DRF序列化和反序列化(二:ModelSerializer)

0015 DRF框架开发(02 创建模型)

drf序列化