custom django model_to_dict with @property and readonly field

1
2
3
4
5
6
7
8
9
10
11
from django.db.models.query_utils import DeferredAttribute
def object_as_dict(obj):
data_dict = {}#{k:getattr(obj, k) for k in dir(obj)}
for k in dir(obj):
try:
if isinstance(getattr(obj.__class__, k), DeferredAttribute) or isinstance(getattr(obj.__class__, k), property):
data_dict[k] = getattr(obj, k)
except Exception as e:
print(e)
print k
return data_dict