django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Add options for excluding None values in serialization

Open cummingscs opened this issue 13 years ago • 5 comments

I have some objects that have a lot of optional attributes, and the expectation is that the output JSON should just have the required and populated attributes.

There should be options to mute None-valued attributes in output.

  • At the serializer level
    • Applied to all contained fields
    • Option to specify at serializer declaration or instantiation.
    • Nested serializers could inherit or override active option
  • At the field level
    • Applied to values of the field
    • Option to specify at field declaration or instantiation.
  • At the renderer level
    • Option to specify at serializer declaration or instantiation.
      • In this case, instantiation-time would likely be most-used option

cummingscs avatar Dec 04 '13 03:12 cummingscs

The serializers are already substantially the most complex part of REST framework, and I'd rather not see that expanding. What I'm generally pushing for with this type of feature request is to see it implemented as a third party package - eg provide a JSON renderer class that drops None fields, or Serializer and ModelSerializer subclasses that do the same. If there are any API hooks that are required to make it possible to do that in a third party app, then we can consider making changes at that level.

There's a decent template for creating a third party app from, here: https://github.com/dabapps/django-reusable-app and I'm more than happy to get stuck into helping with test setup and pypi deployment etc.

It may also be worth taking this sort of feature request to the discussion group - see what other folks have been doing, and if anyone else would also like to get involved in a third party package for it.

We'd then be able to link from the main docs to the package. Let me know your thoughts. :)

lovelydinosaur avatar Dec 04 '13 09:12 lovelydinosaur

Fair enough. I'll built it that way then and see if any core changes are needed.

cummingscs avatar Dec 04 '13 14:12 cummingscs

That would be great - ping this ticket with the repo so anyone else interested can follow it, and make sure to ping this ticket if you need a hand with anything.

lovelydinosaur avatar Dec 04 '13 14:12 lovelydinosaur

I'm re-thinking this anyway, and believing that I was wrong in this. Even if null, a property should be included so that if a consumer wanted to PUT back the same resource with changes, they would:

  • know what all of the options for a resource were
  • be providing back an accurate representation of that resource, not leaving assumptions about the missing properties.

cummingscs avatar Feb 23 '14 18:02 cummingscs

So I'm probably just going to let this lie and not do anything for this for the forseeable future.

cummingscs avatar Feb 23 '14 18:02 cummingscs