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')
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM