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