Here’s a mixin that adds an as_dict
method that will try to convert a model
into a dictionary:
class ModelSerializationMixin(object):
def as_dict(self, fields=None, exclude=None):
"""
Return this model as a dictionary, replacing ForeignKey values with
their pks.
fields - The fields to return. If omitted, returns all fields (minus
excluded).
exclude - The fields to return. If omitted, returns the fields from
`fields`.
"""
data = {}
for field in self._meta.fields:
if exclude and field.name in exclude:
continue
if fields is not None and field.name not in fields:
continue
if hasattr(field, "get_foreign_related_value"):
# If the field is a FK or such, get the foreign ID.
value = field.get_foreign_related_value(self)[0]
else:
value = getattr(self, field.name)
data[field.name] = value
return data
Inherit from it and call as_dict()
on your instance:
class MyModel(models.Model, ModelSerializationMixin):
my_field = models.CharField(max_length=100)
my_fk = models.ForeignKey(OtherModel)
>>> mymodel_instance.as_dict()
{"my_field": "test", "my_fk": 4}