Django REST Framework - StringRelatedField

为了用其__str__方法表示关系的目标,你可以在序列化器中使用StringRelatedField。

# model:
class Post(models.Model):
    # ...

    def __str__(self):
        return f"{self.date_published} - {self.title}"


# serializer:
class TagSerializer(serializers.ModelSerializer):
    posts = serializers.StringRelatedField(many=True)

    class Meta:
        model = Tag
        fields = ['name', 'posts']

# result:
{
    "name": "Stories",
    "posts": [
        "2022-01-09 - My first story",
        "2022-04-09 - Story about a dog"
    ]
}
posted @ 2023-03-13 13:49  公众号海哥python  阅读(109)  评论(0编辑  收藏  举报