drf 自定义响应
I’m currently implementing a RESTful API with Django Rest Framework (a fantastic framework by the way). I’m mostly depending on the automatic serialization that a ModelSerializer provides.
我目前正在使用Django Rest Framework (顺便说一句很棒的框架)实现RESTful API。 我主要取决于ModelSerializer提供的自动序列化。
class class ReportSerializerReportSerializer (( serializersserializers .. ModelSerializerModelSerializer ):
):
class class MetaMeta :
:
model model = = modelsmodels .. Report
Report
fields fields = = (( 'id''id' , , 'name''name' )
)
But sometimes you need extra fields. In my case I wanted to add a readonly image_url field to a serializer. So I added a SerializerMethodField:
但是有时您需要额外的字段。 就我而言,我想向序列化器添加一个只读的image_url字段。 所以我添加了SerializerMethodField :
This looks correct at a first glance, however, my API server would now throw exceptions like this one: ImproperlyConfigured at /api/v1/reports/2 - Field name `logo_url` is not valid for model `ModelBase`.
乍看之下这看起来是正确的,但是,我的API服务器现在会抛出类似这样的异常: 在/ api / v1 / reports / 2中配置不正确-字段名称logo_url对于模型ModelBase无效。
At first I thought it was a naming conflict with a model field or method. But then, the solution turned out to be much simpler: In a moment of mental aberration I must have defined an attribute and a method with the same name.
起初,我认为这是与模型字段或方法的命名冲突。 但是,结果却变得简单得多:在出现精神异常时,我必须定义了一个具有相同名称的属性和方法。
The solution is to use the get_ prefix for the method name:
解决方案是对方法名称使用get_前缀:
class class ReportSerializerReportSerializer (( serializersserializers .. ModelSerializerModelSerializer ):
):
logo_url logo_url = = serializersserializers .. SerializerMethodFieldSerializerMethodField ()
()
class class MetaMeta :
:
model model = = modelsmodels .. Report
Report
fields fields = = (( 'id''id' , , 'name''name' , , 'logo_url''logo_url' )
)
def def get_logo_urlget_logo_url (( selfself , , objobj ):
):
return return objobj .. logologo .. imageimage .. url
url
翻译自: https://www.pybloggers.com/2015/02/properly-defining-serializermethodfields-in-drf/
drf 自定义响应