如何创建基于ID的PUT / POST,但如何在DRF中创建响应中的详细信息? [英] How to create Id based PUT/POST but details in the response in DRF?

查看:144
本文介绍了如何创建基于ID的PUT / POST,但如何在DRF中创建响应中的详细信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是模型具有带有详细信息的外键。例如有两个模型

I have a situation where a model has a foreign key with details. Ex. there are two models

class Person(models):
    country = models.ForeignKey(Country)

class Country(models):
    name = models.CharField(max_length=100)

假定国家已预先创建。现在,我希望 Person 的API在 POST / PUT <中仅采用国家ID / code>请求,但返回该国家/地区的详细信息,而不只是ID。

Assume countries have been created beforehand. Now, I want the APIs for Person to take only country Id in POST/PUT requests but return the details of that country instead of only Id.

Request
{
   "id": 1,
   "country": 9
}
Response
{
   "id": 1,
   "country": {
       "id": 9,
       "name": "Some Country"
    }
}

我正在使用Django Rest框架。 (我可以编写在读取和写入API中都采用 id 或采用整个国家对象的序列化器)

I'm using Django Rest Framework. (I can write serializers which either take id in both read and write APIs or take the entire country object)

推荐答案

您可以为此编写自定义字段 CountryField ,并使用用户 to_representation 方法返回对象详细信息:

You can write custom field CountryField for this and user to_representation method to return object details:

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序列化程序中使用它:

And use it in Person serializer:

class PersonSerializer(serializers.ModelSerializer):
    country = CountryField()

这篇关于如何创建基于ID的PUT / POST,但如何在DRF中创建响应中的详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆