2013-02-18 100 views
1

處理使用Django REST framework我有以下以下串行。我想添加(嵌套)相關對象(ProductCatSerializer)到ProductSerializer。我曾嘗試以下....串行嵌套對象

class ProductCatSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = ProductCat 
     fields = ('id', 'title') 

class ProductSerializer(serializers.ModelSerializer): 
    """ 
    Serializing the Product instances into representations. 
    """ 
    ProductCat = ProductCatSerializer() 

    class Meta: 
     model = Product 
     fields = ('id', 'title', 'description', 'price',) 

所以,我希望發生的是產品展示嵌套在結果中的相關類別。

謝謝。

更新:

使用深度= 2選項(感謝Nandeep馬裏)我現在明白了嵌套值,但他們只使用ID的,而不是keyparis像JSON請求的其餘部分展示(見類別如下)。它幾乎是正確的。

"results": [ 
     { 
      "id": 1, 
      "title": "test ", 
      "description": "test", 
      "price": "2.99", 
      "product_url": "222", 
      "product_ref": "222", 
      "active": true, 
      "created": "2013-02-15T15:49:28Z", 
      "modified": "2013-02-17T13:05:28Z", 
      "category": [ 
       1, 
       2 
      ], 
+0

ProductCatSerializer中的模型不應該是別的嗎?順便說一句,你的名字真的與問題同步。 – 2013-02-18 14:50:25

+0

你試過這個嗎? http://stackoverflow.com/questions/3753359/serializing-foreign-key-objects-in-django – 2013-02-18 14:52:16

+0

對不起,輸入例子時只是一個錯誤,道瓊斯!糾正。名字是大聲笑:) – jason 2013-02-18 14:52:23

回答

1

你舉的例子幾乎是正確的,但你應該叫場「productcat」(或任何模型relationshipt被調用,但沒有駝峯),並將其添加到您的領域。

class ProductCatSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = ProductCat 
     fields = ('id', 'title') 

class ProductSerializer(serializers.ModelSerializer): 
    """ 
    Serializing the Product instances into representations. 
    """ 
    productcat = ProductCatSerializer() 

    class Meta: 
     model = Product 
     fields = ('id', 'title', 'description', 'price', 'productcat') 
+0

完美,我在學習,慢慢地,但學習!再次感謝湯姆。 – jason 2013-02-19 10:02:52