2015-04-18 90 views
2

我有CategoryArticle模型,Article有一個外鍵引用Category,在我serializer我可以得到,因爲_ _str__方法的分類模型的名稱列,但我怎麼能在Category模型得到其他列如何在Django-rest-framework序列化程序中的關係模型中獲得額外的列?

models.py:

# blog category models 
class Category(models.Model): 
    #id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True) 
    name = models.CharField(max_length=50,help_text='category name') 
    description = models.TextField(default='',help_text='category description') 
    coverimg = models.CharField(max_length=200,default='',help_text='category front cover image') 
    covercolor = models.CharField(max_length=7,default='#ffffff',help_text='color for each category background') 
    totalitems = models.IntegerField(default=0,help_text='total items for each category') 
    createtime = models.DateTimeField(auto_now_add=True) 
    modifytime = models.DateTimeField(auto_now=True) 

    categories = models.Manager() 

    class Meta: 
     db_table = 'article_category' 
    def __str__(self): 
     return self.name 

#blog article models 
class Article(models.Model): 
    STATUS = (
     (0,'on'), 
     (1,'off') 
    ) 
    #id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True) 
    category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category') 
    #author = models.ForeignKey(myadmin.User, help_text='foreigner key reference myadmin User') 
    title = models.CharField(max_length=100, help_text='article title') 
    description = models.TextField(help_text='article brief description') 
    content = models.TextField(help_text='article content') 
    like = models.IntegerField(default=0,help_text='like numbers') 
    secretcode = models.CharField(max_length=512,help_text='who has the code can scan') 
    status = models.IntegerField(choices=STATUS,help_text='status of the article') 
    createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created') 
    modifytime = models.DateTimeField(auto_now=True,help_text='time when modified') 

    articles = models.Manager() 

    def __str__(self): 
     return self.title 
    class Meta: 
     db_table = 'article' 

    def save(self, *args, **kwargs): 
     if not self.id: 
      Category.categories.filter(pk=self.category.pk).update(totalitems = F('totalitems')+1) 
     super(Article,self).save(*args, **kwargs) 

serializers.py:

# Article catalog 
class ArticleCatalogSerializer(serializers.ModelSerializer): 
    category = serializers.StringRelatedField() 
    articletags = serializers.StringRelatedField(many=True) 
    covercolor = serializers.StringRelatedField() 
    class Meta: 
     model = Article 
     fields = ('id', 'title', 'category', 'articletags', 'description', 'like', 'createtime', 'covercolor') 

海灣rcolor = serializers.StringRelatedField()將導致一個錯誤:Article' object has no attribute 'covercolor和我改變到這樣的:

改變serializers.py:

# category serializer for ArticleCatalogSerializer for nested relationship 
class CategoryNestedRelationshipSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Category 
     fields = ('covercolor',) 

# Article catalog 
class ArticleCatalogSerializer(serializers.ModelSerializer): 
    category = serializers.StringRelatedField() 
    articletags = serializers.StringRelatedField(many=True) 
    covercolor = CategoryNestedRelationshipSerializer(read_only=True) 
    class Meta: 
     model = Article 
     ields = ('id', 'title', 'category', 'articletags', 'description', 'like', 'createtime', 'covercolor') 

得到了一個錯誤:

Got AttributeError when attempting to get a value for field `covercolor` on serializer `ArticleCatalogSerializer`. 
The serializer field might be named incorrectly and not match any attribute or key on the `Article` instance. 
Original exception text was: 'Article' object has no attribute 'covercolor'. 

如何實現這一點?

回答

3

在你的編輯,更改ArticleCatalogSerializer到

class ArticleCatalogSerializer(serializers.ModelSerializer): 
    category = CategoryNestedRelationshipSerializer() 
    class Meta: 
     model = Article 

你會以這種形式獲得輸出

{ 
"id": 1, 
"category": { 
"covercolor": "#ffffff" 
}, 
"title": "sa", 
"description": "bhjghj", 
"content": "sda", 
"like": 0, 
"secretcode": "77", 
"status": 0, 
"createtime": "2015-04-18T07:52:57.230110Z", 
"modifytime": "2015-04-18T07:52:57.230135Z" 
} 

如果你想類別的任何其他列,您可以在您的類別串包括像這個

class CategoryNestedRelationshipSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Category 
     fields = ('covercolor','name','description') 
+0

這工作完美。在模型中,如果您引用與關係模型相關的任何列,外鍵應該是入口,在前一種情況下,我只引用返回其名稱的類別外鍵,只有一列,如果有很多列,你應該在關係模型上查詢它們,並使它成爲一個嵌套關係,並插入到Article中,這是一個數組。我想對不對? –

+2

的確如此,你明白了.. – Pawan

+0

謝謝,玩得開心:) –

0

StringRelatedField將發出相關字段的字符串表示形式。

要保持'平'格式,您需要編寫一個custom字段。

或者,如果您想要包含對類別的某些引用,則需要PrimaryKeyRelatedField或nest相關模型。

+0

我改爲** covercolor = serializers.PrimaryKeyRelatedField(read_only = True)** stil我不工作〜 –

+0

啊,如果你序列化一個文章模型,那麼這將是因爲covercolor屬性(它在相關的類別)。要保持'平面'格式,您需要編寫一個自定義字段。 –

+0

我編輯了我的問題,看一看,我錯了? –

相關問題