2016-11-13 130 views
0

我有兩個型號Django的REST框架模型外鍵

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創建項目?

回答

0

我自己的答案質疑: 先加extra_kwargs項串行:

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

添加後創建方法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 
0

這裏有一個很好的解決方案Django Rest Framework writable nested serializers 此是這裏幾乎是同樣的問題。

這裏的區別是ForeignKey是用來代替ManyToMany這將導致required field error

添加extra_kwargs解決了這個問題,還有另一種方法是增加空=真到外鍵字段

order = models.ForeignKey(Order, related_name='items', null=True) 
相關問題