【问题标题】:Retrieve nested dict from Django nested queryset with ForeignKey?使用 ForeignKey 从 Django 嵌套查询集中检索嵌套字典?
【发布时间】:2017-09-08 13:35:40
【问题描述】:

我有一个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 中,我想以 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”的方法是什么?

【问题讨论】:

  • 请出示您的序列化器
  • 你在使用 Django Rest 框架吗?如果没有,你应该是。
  • 是的,我正在使用它
  • 我的序列化器是什么意思?这只是一个概念性的例子

标签: python django serialization django-models django-rest-framework


【解决方案1】:

你要找的是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"
    }
 }

【讨论】:

  • 非常感谢 :) 这是完美的 :)
猜你喜欢
  • 2020-10-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2019-09-06
  • 2013-09-05
  • 1970-01-01
相关资源
最近更新 更多