如何序列化关系

时间:2016-06-09 08:50:59

标签: json django django-rest-framework

尝试将一些JSON发布到我的API 串行器:

from rest_framework import serializers
from models import Order, OrderProduct, Delivery, Payments

class DeliverySerializer(serializers.ModelSerializer):
    class Meta:
        model = Delivery
        fields = ('delivery_time','delivery_adress','phone')#'id', 
    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Delivery.objects.create(**validated_data)   


class PaymentsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Payments
        #fields = (title) #'id',
    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Payments.objects.create(**validated_data)   



class OrderSerializer(serializers.ModelSerializer):

    delivery = DeliverySerializer(required=False, allow_null=True)
    paymentMethod = PaymentsSerializer(required=False, allow_null=True)
    class Meta:
        model = Order
        fields = ( 'delivery', 'paymentMethod','summ','success') #'id',

    def create(self, validated_data):
        deliverys_data = validated_data.pop('delivery')
        paymentsMethod_data = validated_data.pop('paymentMethod')
        order = Order.objects.create(**validated_data)  
        Delivery.objects.create(order=order,**deliverys_data)
        Payments.objects.create(order=order,**paymentsMethod_data)
        return order   

查看:

api_view(['POST'])
def order_post(request, format=None)

    if request.method == 'POST':
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当1尝试在数据库中下订单时,我得到:

return Database.Cursor.execute(self, query, params)
IntegrityError: order_order.delivery_id may not be NULL

我只是尝试从字段中删除id,将id添加到字段,结果是相同的。

JSON:

{"delivery":{"delivery_time":"2016-05-31T12:18:47Z","delivery_adress":"123","phone":"123"},"paymentMethod":{"id":1,"title":"123124123"},"summ":"23","success":false}

{"delivery":{"id":"1","delivery_time":"2016-05-31T12:18:47Z","delivery_adress":"123","phone":"123"},"paymentMethod":{"id":"1","title":"123124123"},"summ":"23","success":false}

UPD1。 机型:

from __future__ import unicode_literals

from django.db import models

# Create your models here.
class Order (models.Model):
    id = models.AutoField(primary_key=True)
    date_create = models.DateField(auto_now_add=True)
    date_change = models.DateField(auto_now=True)
    summ =models.CharField(max_length=15,default='0')
    delivery = models.ForeignKey('Delivery')
    success = models.BooleanField(default=False)
    paymentMethod = models.ForeignKey('Payments')
    def __unicode__(self):
        return unicode(self.id)

class OrderProduct(models.Model):
    order=models.ForeignKey('Order')
    id = models.AutoField(primary_key=True)
    date_create = models.DateField(auto_now_add=True)
    date_change = models.DateField(auto_now=True)
    price = models.IntegerField()
    product = models.ForeignKey('product.Product')
    additionals = models.IntegerField(null=True,default=0)
    count = models.IntegerField()
    def __unicode__(self):
            return self.id


class Delivery(models.Model):
    id = models.AutoField(primary_key=True)
    date_create = models.DateField(auto_now_add=True)
    date_change = models.DateField(auto_now=True)
    delivery_time = models.DateTimeField()
    delivery_adress = models.TextField()
    phone = models.TextField()
    def __unicode__(self):
            return self.phone

class Payments(models.Model):
    id = models.AutoField(primary_key=True)
    date_create = models.DateField(auto_now_add=True)
    date_change = models.DateField(auto_now=True)
    title = models.TextField();
    def __unicode__(self):
            return self.title             

1 个答案:

答案 0 :(得分:1)

您正在以错误的顺序进行对象创建,这就是您获得IntegrityError: order_order.delivery_id may not be NULL的原因。再次检查模型结构:

您的Order模型有ForeignKey'sDeliveryPayments,这意味着您需要创建DeliveryPayments个对象之前 Order

尝试这样的事情:

def create(self, validated_data):
    deliverys_data = validated_data.pop('delivery')
    delivery = Delivery.objects.create(**deliverys_data)

    paymentsMethod_data = validated_data.pop('paymentMethod')
    payment_method = Payments.objects.create(**paymentsMethod_data)

    order = Order.objects.create(
        delivery=delivery,
        paymentMethod=payment_method,
        **validated_data
    )

    return order