【问题标题】:Django model rendering number instead of stringDjango模型渲染数字而不是字符串
【发布时间】:2022-06-25 20:02:38
【问题描述】:

我正在创建一个博客站点,其中有作者发布博客等。问题在于呈现作者的姓名,而不是 django 返回一个数字。

我的博客模型:

class Blog(models.Model):
    title=models.CharField(max_length=255)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted=models.DateTimeField(auto_now_add=True)
    body=models.TextField()

    def __str__(self):
        return self.title

还有我的序列化器:

    class Meta:
        model=Blog
        fields=('title', 'author', 'body', 'date_posted')

但是,在 django rest 框架中,当它应该是“管理员”用户时,它会呈现一个数字:

[
{
        "title": "First Blog",
        "author": 1,
        "body": "Example blog text",
        "date_posted": "2022-05-18T23:55:21.529755Z"
    }
]

有点困惑,因为没有错误,它只是没有呈现“管理员”。任何帮助都会有所帮助,谢谢。

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    它显示了用户对象的主键,这是存储在外键字段中的内容。

    要遵循用户对象的用户名(并假设您没有用户序列化程序),您可以创建一个自定义字段,例如,

    class Meta:
        model=Blog
        fields=('title', 'author', 'author_name', 'body', 'date_posted')
    
    author_name = serializers.SerializerMethodField('get_author_name')
    
    def get_author_name(self, obj):
        return obj.author.username
    

    【讨论】:

      【解决方案2】:

      要获取完整的作者数据,您需要在BlogSerializer 中添加UserSerializer。

      class BlogSerializer(serializers.ModelSerializer):
          author = UserSerializer(read_only = True)
      
          class Meta:
              model = Blog
              fields = ('title', 'author', 'author_name', 'body', 'date_posted', )
      
          
      

      【讨论】:

        猜你喜欢
        • 2015-04-15
        • 2014-11-27
        • 2023-02-21
        • 2020-09-02
        • 2014-02-28
        • 2022-11-18
        • 1970-01-01
        • 2018-10-09
        • 2013-07-11
        相关资源
        最近更新 更多