Python 如何在Django rest框架序列化程序的关系模型中获得额外的列?

Python 如何在Django rest框架序列化程序的关系模型中获得额外的列?,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我有Category和Article模型,Article有一个外键referenceCategory,在我的序列化程序中我可以在Category模型中获得name列,因为使用了str方法,但是如何在Category模型中获得其他列呢 models.py: # blog category models class Category(models.Model): #id = models.IntegerField(primary_key=True,help_text='primary key

我有
Category
Article
模型,
Article
有一个外键reference
Category
,在我的
序列化程序中
我可以在Category模型中获得name列,因为使用了str方法,但是如何在
Category
模型中获得其他列呢

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')
covercolor=serializers.StringRelatedField()将导致错误:
Article'对象没有属性'covercolor
,我更改为:

已更改序列化程序。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'.
出现错误:

#   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'.

如何实现这一点?

StringRelatedField将发出相关字段的字符串表示

要保持“平面”格式,您需要编写一个字段


或者,如果希望包含对类别的引用,则需要PrimaryKeyRelatedField或相关模型。

在编辑中,将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')

我改为covercolor=serializers.PrimaryKeyRelatedField(read_only=True)仍然不起作用~Ahh,如果你正在序列化一个文章模型,那是因为covercolor属性(它在相关类别上)。要保持“平面”格式,您需要编写一个自定义字段。我已经编辑了我的问题,看看,我哪里错了?这非常有效。在模型中,如果引用与关系模型相关的任何列,外键应该是入口,在前一种情况下,我只引用类别外键,它返回其名称,只有一列,若有很多列,你们应该在关系模型上查询它们,并将其设置为嵌套关系并插入到文章中,这是一个数组。我想对了吗?节省了我的时间。。。谢谢