【问题标题】:Django model - how to display class' property with foreign key in rest apiDjango模型-如何在rest api中使用外键显示类的属性
【发布时间】:2017-12-01 04:12:07
【问题描述】:

serializers.py:

class PostSerializer(ModelSerializer):
    class Meta:
        model=Post
        fields=[
            'author',
            'title',
            'content',
            'likes',
        ]

models.py:

class User(models.Model):

    name=models.CharField(max_length=255)
    surname=models.CharField(max_length=255)
    email=models.EmailField(max_length=255)
    username=models.CharField(max_length=255)
    password=models.CharField(max_length=2048)
    logged_in=models.BooleanField(default=False)

    def __str__(self):
        self.full_name=self.name+' '+self.surname
        return self.full_name


class Post(models.Model):
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    title=models.CharField(max_length=255)
    content=models.TextField()
    likes=models.IntegerField(default=0)

我的问题是,

我如何通过序列化器在 Rest API 中显示来自 Post 模型类的 author.name,因为序列化器字段从给定类中获取文字参数名称?

【问题讨论】:

  • 也许嵌套序列化程序可以提供帮助? django-rest-framework.org/api-guide/serializers/…
  • 我不认为它可以帮助我,或者我不知道如何实现它?有什么例子吗?
  • 另一种选择可能是使用 SerializerMethodField 命名任何您想要的名称,并使用 get_field_name 方法通过关系获取您想要的值。我现在正在使用移动设备,但我会尽快发布答案。

标签: django python-3.x django-models django-rest-framework


【解决方案1】:

假设您想要一个只读字段,SerializerMethodField 应该可以解决问题。请尝试以下操作:

from rest_framework import serializers

class PostSerializer(ModelSerializer):
    author = serializers.SerializerMethodField()

    def get_author(self, obj):
        return obj.author.name

    class Meta:
        model=Post
        fields=[
            'author',
            'title',
            'content',
            'likes',
        ]

【讨论】:

  • 我试过了,这是我得到的错误'PostSerializer' object has no attribute 'get_author'
  • 起来,我的错。它工作正常。我在代码中写了一些不好的东西。谢谢你,先生!
  • 没问题!快乐的 django-ing!
猜你喜欢
  • 2013-02-07
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2020-07-03
  • 2018-04-25
  • 2011-10-23
  • 2023-03-23
相关资源
最近更新 更多