Django REST框架 - 序列化可选字段 [英] Django REST Framework - Serializing optional fields

查看:805
本文介绍了Django REST框架 - 序列化可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可选字段的对象。我已经以这种方式定义了我的序列化:

  class ProductSerializer(serializers.Serializer):
code = serializers.Field source =Code)
classification = serializers.CharField(source =Classification,required = False)

想法 required = False 将会执行绕过该字段的工作(如果不存在)。但是,在文档中提到这会影响反序列化而不是序列化。



我收到以下错误:

 '产品'对象没有属性'分类'

当我尝试访问序列化实例的 .data 时发生这种情况。 (这是不是意味着它是反序列化提高这个?)



这种情况发生在没有分类 。如果我从序列化器类中省略了分类,它的工作原理很好。



如何正确地执行此操作?序列化可选字段的对象,即。

解决方案

序列化程序故意设计为使用一组固定的字段,以便您您可以轻松地选择退出其中一个按键。



您可以使用 SerializerMethodField 返回字段值或如果字段不存在,或者您根本无法使用序列化程序,只需编写一个直接返回响应的视图。



REST框架3.0更新 serializer.fields 可以在实例化的串行器上修改。当需要动态串行化器类时,我可能会建议在自定义的 Serializer .__ init __()方法中更改字段。


I have an object that has optional fields. I have defined my serializer this way:

class ProductSerializer(serializers.Serializer):
    code = serializers.Field(source="Code")
    classification = serializers.CharField(source="Classification", required=False)

I thought required=False would do the job of bypassing the field if it doesn't exist. However, it is mentioned in the documentation that this affects deserialization rather than serialization.

I'm getting the following error:

'Product' object has no attribute 'Classification'

Which is happening when I try to access .data of the serialized instance. (Doesn't this mean it's deserialization that's raising this?)

This happens for instances that do not have Classification. If I omit Classification from the serializer class it works just fine.

How do I correctly do this? Serialize an object with optional fields, that is.

解决方案

The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys.

You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly.

Update for REST framework 3.0 serializer.fields can be modified on an instantiated serializer. When dynamic serializer classes are required I'd probably suggest altering the fields in a custom Serializer.__init__() method.

这篇关于Django REST框架 - 序列化可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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