Sometimes, we want to convert Python Django Model object to dict with all of the fields intact.
In this article, we’ll look at how to convert Python Django Model object to dict with all of the fields intact.
How to convert Python Django Model object to dict with all of the fields intact?
To convert Python Django Model object to dict with all of the fields intact, we can create our own custom function.
For instance, we write
from itertools import chain
def to_dict(instance):
opts = instance._meta
data = {}
for f in chain(opts.concrete_fields, opts.private_fields):
data[f.name] = f.value_from_object(instance)
for f in opts.many_to_many:
data[f.name] = [i.id for i in f.value_from_object(instance)]
return data
to create the to_dict
function that gets the model instance
as the parameter.
In it, we loop through the concrete_fields
and private_fields
comnbined into one iterator with chain
.
And we add the entries to the data
dict after calling value_from_object
with instance
to get the object from the value before putting them into the dict.
And then we loop through the many_to_many
items and put them many to many items into a list before we put them into the data
dict.
We use value_from_object
to convert the values to objects.
Finally, we return the data
dict.
Conclusion
To convert Python Django Model object to dict with all of the fields intact, we can create our own custom function.