Skip to content

Instantly share code, notes, and snippets.

@bohde
Created February 7, 2012 02:15
Show Gist options
  • Select an option

  • Save bohde/1756675 to your computer and use it in GitHub Desktop.

Select an option

Save bohde/1756675 to your computer and use it in GitHub Desktop.
from tastypie.fields import ToMany
class HrefToMany(ToMany):
"""Like a normal ToMany, except dehyrates to a link to a filtered collection"""
def uri_template(self):
if not hasattr(self, '_uri_template'):
self._uri_template = self.make_uri_template()
return self._uri_template
def make_uri_template(self):
related = self.get_related_resource(None)
base = related.get_resource_list_uri()
# This may fail
field_name = next(k for k,v in related.fields.iteritems() if v == self._cls)
return ''.join([base, "?", field_name, '__id=%s'])
def dehydrate(self, bundle):
if not bundle.obj or not bundle.obj.pk:
if not self.null:
raise ApiFieldError("The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)
return None
return self.uri_template % (bundle.obj.pk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment