14

I am a beginner in Django. And I need to convert Model instance in to dictionary similar as Model.objects.values do, with relation fields. So I write a little function to do this:

def _get_proper(instance, field):
    if field.__contains__("__"):
        inst_name = field.split("__")[0]
        new_inst = getattr(instance, inst_name)
        next_field = "__".join(field.split("__")[1:])
        value = _get_proper(new_inst, next_field)
    else:
        value = getattr(instance, field)

    return value

def instance_to_dict(instance, fields):
    return {key: _get_proper(instance, key) for key in fields}

So, i can use it in such way:

user_obj = User.objects.select_related(...).get(...)
print instance_to_dict(user_obj, ["name", "city__name", "city_id"])

May you propose the better solution? Thanks! P.S. Sorry for my English.

Taras Protsenko
  • 545
  • 1
  • 6
  • 15
  • 3
    Possible duplicate of [Convert Django Model object to dict with all of the fields intact](http://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of-the-fields-intact) – Zags Oct 18 '16 at 20:44

1 Answers1

27

This actually already exists in Django, but its not widely documented.

from django.forms import model_to_dict
my_obj = User.objects.first()
model_to_dict(my_obj,
    fields = [...], # fields to include
    exclude =  [...], # fields to exclude
)
Sachin Kolige
  • 363
  • 2
  • 7