gpt4 book ai didi

python - 使用ForeignKey从Django嵌套查询集中检索嵌套字典?

转载 作者:行者123 更新时间:2023-12-01 02:36:56 29 4
gpt4 key购买 nike

我有一个 models.py 具有:

class Other(models.Model):
name = models.CharField(max_length=200)

class ModelA(models.Model):
name = models.CharField(max_length=200)
other = models.ForeignKey(Other, on_delete=models.PROTECT)

在我的 REST API 中,我想像这样检索 JsonResponse 的 json:

{
"modelA": {
"id": "modelA id automatically assigned by django model",
"name": "my modelA name",
"other": {
"id": "other thing id also automatically assigned by django model",
"name": "other thing name"
}
}
}

最“Pythonic”的方法是什么?

最佳答案

您正在寻找的是nested serialization .

在您的 serializers.py 中,您应该使用 Other 模型内部 ModelA 模型的序列化器>.

serializers.py中:

from rest_framework import serializers

from .models import Other, ModelA


class OtherSerializer(serializers.ModelSerializer):
class Meta:
model = Other
fields = ('id', 'name')


class ModelASerializer(serializers.ModelSerializer):
other = OtherSerializer(read_only=True)
# The magic happens here.
# You use your already created OtherSerializer inside the one for ModelA
# And that will perform nested serialization
# Which will produce the result that you want

class Meta:
model = ModelA
fields = ('id', 'name', 'other')
# _________________________^

现在你得到的结果如下:

{
"id": 1,
"name": "my modelA name",
"other": {
"id": 1,
"name": "other thing name"
}
}

关于python - 使用ForeignKey从Django嵌套查询集中检索嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117775/

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