- Author:
- SmileyChris
- Posted:
- April 23, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 3 (after 3 ratings)
Useful for when you want to use an instance's values as the initial values of a form which you didn't use form_for_instance
to create.
Handles foreign keys and many-to-many fields just fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def instance_dict(instance, key_format=None):
"Returns a dictionary containing field names and values for the given instance"
from django.db.models.fields.related import ForeignKey
if key_format:
assert '%s' in key_format, 'key_format must contain a %s'
key = lambda key: key_format and key_format % key or key
d = {}
for field in instance._meta.fields:
attr = field.name
value = getattr(instance, attr)
if value is not None and isinstance(field, ForeignKey):
value = value._get_pk_val()
d[key(attr)] = value
for field in instance._meta.many_to_many:
d[key(field.name)] = [obj._get_pk_val() for obj in getattr(instance, field.attname).all()]
return d
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
The function didn't handle dates correctly, at least when feeding instance data to a form with a SelectDateWidget.
I also wanted to use it for unsaved objects, but they failed on many-to-many fields.
Here's a version which fixes both these problems:
#
I've wanted one that could traverse foreign keys.
This adds on the date improvement version above and is tested on django 1.4.
Foreign keys come back as foreignkeyname.foreignkeyvalue in the dictionary, it's recursive so will pull back all the relations (only tested with one level of foreignkey).
#
This turned out to be incompatible with django-filer so I've added a hasattr test.
Now tested + working on django 1.4.1
#
Previous versions did not properly handle inherited models, or ImageFields
#
How about if we use:
from django.forms.models import model_to_dict
model_to_dict(instance, fields=[field.name for field in instance._meta.fields])
#
Please login first before commenting.