2015-12-23 59 views
1

我有一个项目模型,其中包含常见的属性,我有三个不同的子模型FoodItem,ClothesItem和ElectronicItem。使用子模型在一个串行器中创建模型

如果我在POST请求中传递子模型的ItemType和必填字段,我希望在一次调用中创建两个对象,而无需使用一对一关系调用两个序列化程序。我发现这个问题有几个问题,但它是在创建子模型时抱怨item_id缺失。

代码例如:

class Item(models.Model): 
     ITEMTYPE = (
      (1, 'Food'), 
      (2, 'Clothes'), 
      (3, 'Electronic') 
     ) 
     itemType = models.IntegerField(choices=ITEMTYPE) 
     description = models.CharField(max_length=255,blank=True) 
     date_created = models.DateTimeField(auto_now_add=True) 
     date_modified = models.DateTimeField(auto_now=True, null=True) 
     date_deleted = models.DateTimeField(blank=True, null=True) 
     price = models.IntegerField() 

class FoodItem(models.Model): 
     item = models.OneToOneField(Item, blank=True) 
     foodType = models.CharField(max_length=255,blank=True) 
     calories = models.IntegerField() 
+0

在view.py中显示你的代码,并在运行时出现错误 – phourxx

+0

这是嵌套的序列化程序。您需要重写嵌套序列化器中的create方法.http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations – Netro

回答

0

至于可以通过显式定义的字段,并使用source参数为指向相关的型号名平坦化数据串行化器:源=“food_item.calories”例如。

至于创作,你需要通过将串行的validated_data foodTypecalories提供先前创建的Item例如第一,然后FoodItem创建Item实例。