时间:2021-05-22
我使用django-rest-framework开发了一个API.
我正在使用ModelSerializer返回模型的数据.
models.py
class MetaTags(models.Model): title = models.CharField(_('Title'), max_length=255, blank=True, null=True) name = models.CharField(_('Name'), max_length=255, blank=True, null=True)serializer.py
class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags响应
{ "meta": { "title": null, "name": "XYZ" }}理想情况下,在API响应中,不应在响应中发送任何不存在的值.
当标题为null时,我希望响应为:
{ "meta": { "name": "XYZ" }}您可以尝试覆盖to_native函数:
class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_native(self, obj): """ Serialize objects -> primitives. """ ret = self._dict_class() ret.fields = self._dict_class() for field_name, field in self.fields.items(): if field.read_only and obj is None: continue field.initialize(parent=self, field_name=field_name) key = self.get_field_key(field_name) value = field.field_to_native(obj, field_name) # Continue if value is None so that it does not get serialized. if value is None: continue method = getattr(self, 'transform_%s' % field_name, None) if callable(method): value = method(obj, value) if not getattr(field, 'write_only', False): ret[key] = value ret.fields[key] = self.augment_field(field, field_name, key, value) return ret我基本上从serializers.BaseSerializer复制了基本的to_native函数,并添加了一个值的检查.
更新:
至于DRF 3.0,to_native()被重命名为to_representation(),其实现稍有改变.这是DRF 3.0的代码,它忽略空值和空字符串值:
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = OrderedDict() fields = self._readable_fields for field in fields: try: attribute = field.get_attribute(instance) except SkipField: continue # KEY IS HERE: if attribute in [None, '']: continue # We skip `to_representation` for `None` values so that fields do # not have to explicitly deal with that case. # # For related fields with `use_pk_only_optimization` we need to # resolve the pk value. check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute if check_for_none is None: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute) return ret翻译自:https://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
django-rest-framework类视图拓展自django的类视图,只是针对数据的序列化和反序列化等逻辑做了封装。django-rest-framewo
在Django中用rest_framework写API,写了一个用户注册的API,并测试成功。本人环境:Django==2.2.1;djangorestfram
前言我们在django-rest-framework解析请求参数文章中完成了接口文档到参数解析,一个完整的流程中还缺少对数据库的操作.本篇内容为django连接
前言我们在django-rest-framework自定义swagger文章中编写了接口,调通了接口文档.接口文档可以直接填写参数进行请求,接下来的问题是如何接
官方文档settings.py配置REST_FRAMEWORK={'DEFAULT_THROTTLE_CLASSES':('rest_framework.thr