toastdriven/django-tastypie — pull request #269 by ryankask (2011-10-19 14:02:55+00:00)
Title: Fields with null=True should dehydrate to None before returning the default

In the current code, when dehydrating a field on a ``ModelResource`` that has ``null=True``, ``None`` should be returned before the default. This is a simple change that just inverts the current logic in ``ApiField.dehydrate``.

Lets say you have Django model like:

class Person(models.Model):
age = models.IntegerField(null=True, blank=True, default=0)

And a standard ``ModelResource`` for it.

If ``one_person.age is None``, then dehydrating the corresponding ``tastypie.fields.IntegerField.dehydrate`` should return ``None``, not the default, 0.

In Django, ``default`` only matters when creating new objects.

Let me know what you think about this reasoning (even though I would always need to use a patched version because we must distinguish between an integer and ``None``).

I've added tests which involved adding a model to the core tests so I could use an ``django.db.models.IntegerField``.

One test failed before and after the patch:

FAIL: test_build_schema (core.tests.resources.ResourceTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/ryan/src/my-django-tastypie/tests/core/tests/resources.py", line 475, in test_build_schema
'default_format': 'application/json'
AssertionError: {'fields': {'view_count': {'nullable': False, 'default': 0, 'readonly': False, '
[truncated]... != {'fields': {'view_count': {'help_text': 'Integer data. Ex: 2673', 'readonly': Fa [truncated]...
Diff is 2793 characters long. Set self.maxDiff to None to see it.