我遇到以下情况:一名用户可以拥有多个个人资料。这是我的模型课。像这样的例子:
models.py:
class Profile:
name=models.Charfield()
class UserProfile:
user=models.ForeignKey(User)
profile = models.ForeignKey(Profile)
serializers.py:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
在这里,我通过 JSON 返回所有用户,但我想添加一个名为 profiles 的新字段,该字段返回用户拥有的所有 ID 配置文件。
{ "id": 1,
"name" : "John"
....
profiles = [1, 2]
}
如何获取(查询)用户拥有的所有配置文件并将它们添加到我的最终 JSON 中?
最佳答案
在 UserSerializer 上将字段配置文件声明为 PrimaryKeyRelatedField
profiles = serializers.PrimaryKeyRelatedField()
默认情况下,此字段是读写的,但您可以使用 read_only 标志更改此行为。
参见docs
关于python - Django休息框架: How serialize two models queryset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475534/