django rest框架模型外键

时间:2016-11-13 08:00:21

标签: django django-models django-rest-framework

我有两个型号

class Order(models.Model):
     fields...

 class OrderItem(models.Model):
     fiels...
     order = models.ForeignKey(Order, related_name='items')

我有两个序列化器:

class CreateOrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        resource_name = 'order-item'
        fields = ('order', 'count')
   .....
class OrderSerializer(serializers.ModelSerializer):
     items = CreateOrderItemSerializer(many=True)
     class Meta:
         model = Order
         resource_name = 'order'
         fields = ('id','items')

我发布了包含这样的项目数组的订单:

{
    'ordername': 'foo',
    'items': [{
        'name': 'foo1',
        },{
        'name': 'foo2',
        },
      ]
}

但我有错误:

"order":["This field is required."]

我怎样才能先创建订单以后用这个orderid创建项目?

2 个答案:

答案 0 :(得分:2)

我自己的回答问题: 首先将extra_kwargs添加到项目序列化程序:

class CreateOrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        resource_name = 'order-item'
        fields = ('order', 'count')
        extra_kwargs = {
            'order': {'required': False},
        }

将order方法添加到orderserializer后:

def create(self, validated_data):
    items_data = validated_data.pop('items')
    order = Order.objects.create(**validated_data)
    for item in items_data:
        item_name = item['name']
        item, created = OrderItem.objects.get_or_create(order=order,name=item_name)
    return order

答案 1 :(得分:0)

这里有一个很好的解决方案Django Rest Framework writable nested serializers 这几乎是同一个问题。

差异在于使用ForeignKey代替ManyToMany,这将导致required field error

添加extra_kwargs解决了这个问题,还有另一种方法是将null = True添加到foreignkey字段

order = models.ForeignKey(Order, related_name='items', null=True)