gpt4 book ai didi

python - 在 Django 中返回与模型一对一的模型信息

转载 作者:行者123 更新时间:2023-12-04 01:20:18 24 4
gpt4 key购买 nike

我有 2 个非常基本的 Django 模型:User 和 UserProfile。我正在使用 REST 框架,并希望在检索所有用户时包含个人资料信息。我已经在互联网上搜索过,但找不到答案。这是我目前正在尝试的:User.objects.all().prefetch_related('userprofile')

我想要返回的是这样的:

[
{'email': 'email@example.com',
'first_name': 'Test',
'last_name': 'McTester'},
{'email': 'user2@example.com',
'first_name': 'Mary',
'last_name': 'McPherson'}
]

其中名字和姓氏是配置文件属性。我已经能够使用 Flask 和 GraphQL 做类似的事情,但想知道这是否可以在 Django 中使用 REST。

最佳答案

嗯,什么prefetch_related确实是根据 User 模型和 UserProfile 模型之间的关系预先从 UserProfile 模型加载数据,所以当你调用 user.userprofile 它不会再次访问数据库。但是当您调用 user 时它不会返回值。所以在你的model serializer , 您可以使用 source 添加这两个字段指向 UserProfilefirst_namelast_name。例如:

class UserSerializer(serializer.ModelSerializer):
first_name = serializer.CharField(source='userprofile.first_name', read_only=True)
last_name = serializer.CharField(source='userprofile.last_name', read_only=True)

class Meta:
model = User
fields = ['email', 'first_name', 'last_name']

关于python - 在 Django 中返回与模型一对一的模型信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747578/

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