2015-07-21 148 views
4

我試圖保存具有引用另一個表的外鍵的模型對象。試圖編寫相同的序列化程序,但無法包裝我的頭如何做到這一點,似乎無法找到正確的文檔。我的模型對象:Django串行器保存具有外鍵關係的模型

class Restaurant(models.Model): 

    name = models.CharField(null=False, max_length=255) 
    min_order = models.CharField(null=False, max_length=255) 
    # And so on 

class RMenuCategory(models.Model): 

    category_name = models.CharField(null=False, max_length=255) 
    restaurant = models.ForeignKey('Restaurant') 

我串類RMenuCategory型號:

class RestaurantMenuSerializer(serializers.ModelSerializer): 

    restaurant = serializers.PrimaryKeyRelatedField() 

    class Meta: 
     model = RMenuCategory 
     fields = ('id', 'category_name', 'restaurant') 

使得API調用使用JSON爲:

{ "category_name" : "Italian", "restaurant_id" : 4} 

這不工作時,我嘗試了在我看來:

menu_cat = RestaurantMenuSerializer(data=data) 
     if menu_cat.is_valid(): 
      category = menu_cat.save() 
     else: 
      exit() 

回答

3

更改restaurant_idrestaurant

{ "category_name" : "Italian", "restaurant" : 4}