Created
May 21, 2014 22:31
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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