Skip to content

Instantly share code, notes, and snippets.

@thomasyip
Created August 25, 2012 21:35
Show Gist options
  • Save thomasyip/3471186 to your computer and use it in GitHub Desktop.
Save thomasyip/3471186 to your computer and use it in GitHub Desktop.
Custom `hydrate_m2m` method to workaround tastypie bug on creating model with dependent model
# Say, you have models `Invoice` and `InvoicePart`. The `InvoicePart`
# has a non-nullable field of `Invoice`.
#
# Currently (August 2012), `tastypie` will throw an error when you try
# to create (`HTTP Post`) a new `Invoice` that contains one or more new
# `InvoicePart`.
#
# The problem is that when `tastypie` processes the `InvoicePart`, the
# backlink to `Invoice` is not set.
#
# The following custom method worked around the problem. Let me know if
# you find it useful.
class YourModelResource(ModelResource):
def get_backlink(self, field_object):
cls = field_object.to_class()
for cls_field_name, cls_field_object in cls.fields.items():
if not getattr(cls_field_object, 'is_related', False):
continue
if cls_field_name == self.Meta.resource_name:
if cls_field_object.to_class().Meta == self.Meta:
return cls_field_name, cls_field_object
return None, None
def hydrate_m2m(self, bundle):
if bundle.obj is not None and bundle.obj.pk is not None:
uri = self.get_resource_uri(bundle.obj)
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_m2m', False):
continue
backlink_name, backlink_object = self.get_backlink(field_object)
if backlink_object is not None:
related_objects = (bundle.data[field_name]
if field_name in bundle.data else [])
for related in related_objects:
if not backlink_name in related:
related[backlink_name] = uri
return super(ModelResource, self).hydrate_m2m(bundle)
@thomasyip
Copy link
Author

Turned out the problem was caused by missing related_name.

Got inspired by answer here:
http://stackoverflow.com/questions/10582449/creating-related-resources-with-tastypie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment