gpt4 book ai didi

python - Django Rest Framework - 在列表中获取完整的相关对象

转载 作者:太空狗 更新时间:2023-10-30 00:49:46 24 4
gpt4 key购买 nike

我是 Django Rest Framework 的新手,我正在尝试使用 DRF 来序列化(相关)对象的列表。

我有以下模型:

class Answer(models.Model):
value = models.CharField(max_length=128)

class User(models.Model):
name = models.CharField(max_length=128)
age = models.PositiveIntegerField()

class UserAnswer(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)

我试图得到的结果是这种形式:

[
{
"name": "myName1",
"answers": [
{
"value": "myFirstAnswer"
},
{
"value": "mySecondAnswer"
},
{
"value": "myThirdAnswer"
},
]
},
{
"name": "myName2",
"answers": [
{
"value": "myFirstAnswer"
},
{
"value": "mySecondAnswer"
},
{
"value": "myThirdAnswer"
},
]
}
]

我现在正在尝试这样做:

class UserAnswerSerializer(serializers.ModelSerializer):
answers = AllUserAnswersSerializer(many=True, read_only=True)
class Meta:
model = User
fields = ('name', 'answers')

但是我得到以下结果:

[
{
"name": "myName1"
},
{
"name": "myName2"
}
]

当我尝试这样做时:

class UserAnswerSerializer(serializers.ModelSerializer):
answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('name', 'answers')

然后我得到以下结果(又是一个例子):

[
{
"name": "myName1",
"answers": [
1,
2,
3
]
},
{
"name": "myName2",
"answers": [
4,
5,
6
]
}
]

我很难完成这项工作,希望有人能告诉我如何将主键转换为实际对象!

谢谢!

最佳答案

在序列化程序中删除 answers 字段的显式定义并添加 depth=1。它应该看起来像这样:

class UserAnswerSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = User
fields = ('name', 'answers')

关于深度的信息:http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

关于python - Django Rest Framework - 在列表中获取完整的相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28721169/

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