toastdriven/django-tastypie — Issue #321: Field's hydrate should work as exact opposite to dehydrate
Author: migajek
Created: 2011-12-30 21:31:33+00:00
State: open

Hi,
while implementing behavior of custom Field, I dealt with a problem of hydrate / dehydrate cycle.
I personally believe hydrate method should return the whole bundle, not only the field value, since it's opposition - dehydrate - returns the whole bundle.

I know it actually might be supposed to return only field values (in both cases), but it might be convenient to be able to split the data into several fields. Anyway, currently its inconsistent.

Please consider the following example:

class MgForeignKey(fields.ForeignKey):
def _get_obj(self, bundle):
from django.core.exceptions import ObjectDoesNotExist
try:
foreign_obj = getattr(bundle.obj, self.attribute)
except ObjectDoesNotExist:
foreign_obj = None
return foreign_obj

def hydrate(self, bundle):
foreign_obj = self._get_obj(bundle)
if not foreign_obj:
return None # TODO: this will fail probably?, let the Tastypie raise the exception

if bundle.data.has_key('%s_id' % self.attribute):
try:
obj = self.to._meta.queryset._clone().get(pk = bundle.data['%s_id' % self.attribute])
except:
obj = None
#bundle.data[self.attribute] = obj
from tastypie.bundle import Bundle
b = Bundle(obj = obj)
return b

def dehydrate(self, bundle):
foreign_obj = self._get_obj(bundle)
if foreign_obj:
bundle.data['%s_id' % self.attribute] = foreign_obj.id
return bundle