使用ForeignKey从Django嵌套查询集中检索嵌套的dict?

时间:2017-09-08 13:35:41

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

我有一个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"这样做的方法?

1 个答案:

答案 0 :(得分:2)

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

现在你得到的结果如下:

uri = URI("https://blockexplorer.com/api/tx/#{:hammer}")