繁体   English   中英

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

[英]Retrieve nested dict from Django nested queryset with ForeignKey?

我有一个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)

在我的其余API中,我想像这样检索json作为JsonResponse:

{
    "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”的方法是什么?

您正在寻找的是嵌套序列化

在您的serializers.py您应该在ModelA的一个内部使用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"
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM