Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Created May 21, 2014 22:31
Show Gist options
  • Select an option

  • Save jaytaylor/bc44fbcc7b62734bde70 to your computer and use it in GitHub Desktop.

Select an option

Save jaytaylor/bc44fbcc7b62734bde70 to your computer and use it in GitHub Desktop.
Mix-in class for Django ORM objects to allow for more robust object instantiation from keyword arguments.
class AutoFkShifterMixIn(object):
def __init__(self, *args, **kw):
"""Automatically translate any foreign keys to the the *_id field if an id rather than an object has been provided. Also removes m2m kwargs (they'll cause Django ORM to error out)."""
for m2m_field in filter(lambda f: f.name in kw, self._meta.many_to_many):
del kw[m2m_field.name]
for fk_field in filter(lambda f: isinstance(f, models.ForeignKey), self._meta.fields):
if fk_field.name in kw and isinstance(kw[fk_field.name], (int, long, str)):
kw['{}_id'.format(fk_field.name)] = kw.pop(fk_field.name)
super(AutoFkShifterMixIn, self).__init__(*args, **kw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment