DRF-序列化器多种模型

时间:2019-03-04 16:03:21

标签: json django python-3.x django-rest-framework deserialization

请帮助!我如何获取此JSON

Settings->Raw View->CodeMirror->User Overrides

因为,使用我的代码,我只检索了此JSON

{
  "campaign": 27,
  "campaignName": "Prueba promo",
  "promotionType": 999,
  "items": [
     { "item_nbr": 1234567890123, "plu": 2},
     { "item_nbr": 12345678901, "plu": 3}
  ]
}

我该怎么办?我阅读了drf文档,但没有用,我在做什么错? 这是我的代码

我的模型。py

{
"items": [],
"campaign": 27,
"campaignName": "Prueba promo",
"promotionType": 999,
"start_date": "2019-03-04T12:02:16.574874-03:00",
"end_date": null,
"active": true
}

这是我的serializer.py

class Item(models.Model):
promocion = models.ForeignKey(Promocion, related_name='items', on_delete=models.CASCADE, null=True)
item_nbr = models.IntegerField(primary_key=True, help_text="Numero de Item")
modular = models.ForeignKey(Modular, on_delete=models.CASCADE, null=True)
price = models.FloatField()
q_min = models.PositiveIntegerField(default=1, help_text="Cantidad mínima")
q_mul = models.PositiveIntegerField(default=1, help_text="Multiplo de cajas cerradas")
vensil1 = models.CharField(max_length=30, help_text="Atributo item relevante")
vensil2 = models.CharField(max_length=30, help_text="Atributo item relevante")
vensil3 = models.CharField(max_length=30, help_text="Atributo item relevante")
FG = "Fleje grande, 1/3 Carta"
FP = "Fleje pequeño 1/6 Carta"
CP = "Carteleria media Carta"
opciones = ((FG, "Fleje grande, 1/3 Carta"),
            (FP, "Fleje pequeño 1/6 Carta"),                
            (CP, "Carteleria media Carta"),)
print_type = models.CharField(choices=opciones, help_text="Fleje a imprimir", max_length=255)
depto = models.IntegerField(default=1, help_text="Departamento")
descri = models.CharField(max_length=100, help_text="Descripción producto")
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True)
vendor_pack = models.IntegerField(default=1)
container = models.CharField(max_length=6, default="MAY")
size = models.CharField(max_length=20, help_text="Tamaño pack")
cont_net = models.FloatField(default=1, help_text="Contenido Neto")
sell_unit = models.CharField(max_length=5, help_text="Unidad de venta")
weight_drain = models.FloatField(default=0, help_text="Peso drenado")
cod_bal = models.IntegerField(null=True, blank=True, help_text="Código balanza")
plu = models.BigIntegerField(help_text="Código de barra")

def __str__(self):
    return str(self.item_nbr) + ' - ' + str(self.plu)

class Promocion(models.Model):
    campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True)
    campaignName = models.CharField(max_length=50, null=True)
    promotionType = models.IntegerField()
    priority = models.IntegerField(default=1)
    start_date = models.DateTimeField(default=timezone.now, help_text="Fecha 
 inicio promoción")
    end_date = models.DateTimeField(null=True, blank=True, help_text="Fecha 
 fin promoción")
    active = models.BooleanField(default=True)

我的viewsets.py

class ItemPromoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('item_nbr', 'plu')

class PromoSerializer(serializers.ModelSerializer):
    items = ItemPromoSerializer(many=True, read_only=True)
    #steps = ScalePromoSerializer(many=True)
    class Meta:
         model = Promocion
         fields = ('items', 'campaign', 'campaignName', 'promotionType', 
     'start_date', 'end_date', 'active')

和我的路线。py

class PromoViewSet(viewsets.ModelViewSet):
    queryset = Promocion.objects.all()
    serializer_class = PromoSerializer

请帮助我!我在堆,我尝试做to_internal_value()和to_representation(),但它会回应我 “ non_field_errors”:[“无效的数据。应该是字典,但是有列表。”]

感谢大家!

1 个答案:

答案 0 :(得分:0)

如果在POST请求期间发生此问题,则意味着您需要调整保存数据的方式。 Django REST Framework不支持直接在数据库中编写嵌套对象。

对于这些用例,我通常要做的是

  1. 对于这种复杂的用例,我不使用视图集,相反,我更喜欢使用CreateAPIView,它使我能够使用特定的序列化器来验证输入并显示数据。
  2. 我钩住create中的CreateAPIView,并在同时写入多个表时使用with transaction.atomic():,以确保所有事务在出现错误时均无效。
  3. 我使用2个序列化器,一个用于父模型,一个用于子模型。

您的情况下,代码可能是这样的:

serializer.py

class PromoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Promocion
        fields = ('campaign', 'campaignName', 'promotionType', 'start_date', 'end_date', 'active')

class ItemPromoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('item_nbr', 'plu')

viewsets.py

from rest_framework import status
from django.db import transaction

class PromoCreateAPI(CreateAPIView):
    queryset = Promocion.objects.all()
    serializer_class = PromoSerializer

    # We skip perform_create
    def create(self, request, *args, ***kwargs):
        try:
            items_data = request.data.pop('items')
        except KeyError:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        with transaction.atomic():
            instance = serializer.save()
            # Validate each item
            for item in items_data:
                s = ItemPromoSerializer(data=item)
                s.is_valid(raise_exception=True)
                s.save(campaign=instance)
        headers = self.get_success_headers(serializer.data)
        serializer.data['items'] = items_data
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

当然,此代码未经测试,但是希望它能帮助您找到所需的地方。