How to serialize relation

2019-08-30 08:34发布

Try to post some JSON to my API Serializer:

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   

View:

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)

When 1 try to put order in Database I get :

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

I just try to remove id from fields, add id to fields, the result is the same.

Json:

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

or

{"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. Models:

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条回答
Explosion°爆炸
2楼-- · 2019-08-30 08:45

You are doing the object creations in a wrong order, that's why you get IntegrityError: order_order.delivery_id may not be NULL. Check your model structures again:

Your Order models has ForeignKey's to Delivery and Payments, which means that you need to create Delivery and Payments objects before Order.

Try something like this:

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
查看更多
登录 后发表回答