Created
March 2, 2016 16:41
[django] Model to dict
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
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