我遇到的情况是模型具有包含详细信息的外键。前任。有两种型号
class Person(models):
country = models.ForeignKey(Country)
class Country(models):
name = models.CharField(max_length=100)
假设国家/地区已预先创建。现在,我想要 Person
的 API仅取country Id
在POST/PUT
请求但返回该国家/地区的详细信息,而不仅仅是 ID。
Request
{
"id": 1,
"country": 9
}
Response
{
"id": 1,
"country": {
"id": 9,
"name": "Some Country"
}
}
我正在使用 Django Rest 框架。 (我可以编写序列化程序,它可以在读取和写入 API 中采用 id
或采用整个国家/地区对象)
最佳答案
您可以为此和用户 to_representation
方法编写自定义字段 CountryField
以返回对象详细信息:
class CountryDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ('id', 'name')
class CountryField(serializers.PrimaryKeyRelatedField):
def to_representation(self, value):
country = models.Barcode.objects.get(pk=value.pk)
serializer = CountryDetailSerializer(country)
return serializer.data
def get_queryset(self):
return Country.objects.all()
并在 Person 序列化器中使用它:
class PersonSerializer(serializers.ModelSerializer):
country = CountryField()
关于django - 如何创建基于 ID 的 PUT/POST,但在 DRF 中的响应中创建详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45008549/