Skip to content

Instantly share code, notes, and snippets.

@juanmhidalgo
Created March 2, 2016 16:41
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 juanmhidalgo/a3424c1b81df5dbbf4ed to your computer and use it in GitHub Desktop.
Save juanmhidalgo/a3424c1b81df5dbbf4ed to your computer and use it in GitHub Desktop.
[django] Model to dict
from django.db.models.fields.related import ManyToManyField
def to_dict(instance):
opts = instance._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment