Skip to content

Instantly share code, notes, and snippets.

@mgrouchy
Created May 5, 2010 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgrouchy/390243 to your computer and use it in GitHub Desktop.
Save mgrouchy/390243 to your computer and use it in GitHub Desktop.
map values from dict to django model where values are not necessarily coming from serialization
def bind(self, values, **options):
exclude = options.get('exclude', [])
rename_fields = options.get('rename_fields', {})
for (field_name, field_value) in values.iteritems():
if field_name not in exclude:
if field_name in rename_fields.keys():
field_name = rename_fields[field_name]
field = self._meta.get_field(field_name)
if field.choices:
for choice_key, choice_value in field.choices:
if isinstance(choice_value, (list, tuple)):
for choicegrp_key, choicegrp_value in choice_value
if choicegrp_value == field_value:
field_value = choicegrp_key
else:
if choice_value == field_value:
field_value = choice_key
setattr(self, field.attname, field.to_python(field_value))
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment