Skip to content

Instantly share code, notes, and snippets.

@ruiwen
Created February 13, 2012 15:38
Show Gist options
  • Save ruiwen/1817670 to your computer and use it in GitHub Desktop.
Save ruiwen/1817670 to your computer and use it in GitHub Desktop.
Enable django-piston to POST/PUT models with ForeignKeys
def flatten_dict(self, dct):
out = {}
for field in dct.keys():
fk = self.model._meta.get_field(field)
if isinstance(fk, ForeignKey):
# Determine the target model of the ForeignKey
Klass = fk.rel.to().__class__
d = { Klass._meta.pk.name : dct[field] }
# Grab the instance
i = Klass.objects.get(**d)
out[field] = i
else:
out[field] = dct[field]
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment