如何在文章模型上显示类别名称?

时间:2018-10-11 21:23:02

标签: django django-rest-framework

我想根据其名称(选择)在文章上呈现类别字段。当前,它呈现为一个ID。另外,我希望能够通过输入类别名称(选择)而不是其ID(我目前正在这样做)来更新文章模型。我该如何实施呢?

这是我到目前为止所拥有的。

模型

class Category(models.Model):

      """ 
      Model for Category
      """ 

    CATEGORY_CHOICES = (

        ('Sports', 'Sports'),
        ('Music', 'Music'), 
        ('Drama', 'Drama'),
        ('Money', 'Money'), 
        ('Movies', 'Movies'), 
        ('Cars', 'Cars'),
        ('General', 'General'), 
    )
    name = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default='General',null=False, blank=True)


    def __str__(self):

        return self.name

class Article(models.Model):
      """
      Model for an Article
      """ 

    title = models.CharField(max_length=255, null=False, blank=False)

    description = models.TextField(null=False, blank=False)

    body = models.TextField(null=False, blank=False,)

    category = models.ForeignKey(Category, on_delete=models.CASCADE)

序列化器

class ArticleSerializer(serializers.ModelSerializer):
      """
      Serializer for Article.
      """

    class Meta:
        model = Article

        fields = ('title','description','body',''category')

class CategorySerializer(serializers.ModelSerializer):
      """
      Serializer for Category.
      """

    class Meta:
        model = Category

        fields = ('name',)

电流输出 enter image description here

预期输出 enter image description here

1 个答案:

答案 0 :(得分:0)

您可以将ArticleSerializer更改为具有source属性的category字段作为CharField

class ArticleSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source='category.name')

    class Meta:
        model = Article
        fields = ('title','description','body',''category')

要通过名称更新Article的类别,必须确保nameCategory的唯一字段。如果是,则可以使用SlugRelatedField

category = serializers.SlugRelatedField(slug_field='name')