gpt4 book ai didi

django - 如何在 django rest 框架中包含模型序列化的相关字段?

转载 作者:行者123 更新时间:2023-12-01 09:26:05 24 4
gpt4 key购买 nike

我有两个模型:

class User(models.Model):
username = models.CharField()

class Post(models.Model):
text = models.TextField()
owner = models.ForeignKey(User)

使用这样的序列化器:

from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
owner = serializers.Field(source='owner.id')

class Meta:
model = Post
fields = ['text', 'owner']

我收到所有带有所有者 ID 的帖子。我如何修改序列化程序以获取所有包含整个用户模型的所有者的帖子?

我试过了 from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
owner = serializers.Field(source='owner')

class Meta:
model = Post
fields = ['text', 'owner']

但这只是用用户名替换了 id,而不是我预期的整个模型(因为用户的表示返回用户名字段)。

最佳答案

解决方案是像这样定义 UserSerializer 扩展 ModelSerializer

from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):

class Meta:
model = UserModel
fields = ['id', 'username']

然后在 PostSerializer 中使用:

from myapp import UserSerializer
from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
owner = UserSerializer()

class Meta:
model = PostModel
fields = ['id', 'owner']

关于django - 如何在 django rest 框架中包含模型序列化的相关字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23522084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com