Ответ 1
Вы можете попробовать переопределить функцию 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
Я в основном скопировал базовую функцию to_native из serializers.BaseSerializer
и добавил проверку значения.
ОБНОВЛЕНИЕ: Что касается 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