Disclaimer: I'm coming from PHP, where there's stdClass
, whereas I don't know if something like that exists in Python.
I'm trying to add a few custom properties to Django models and converting them to JSON using json.dumps()
. I tried converting them to dicts, but the custom properties don't get converted too. So I'm trying to convert the models to simple objects like PHP's stdClass
, so that I can add whatever properties I like to it.
Is this possible, or is there an easier way to add custom properties to a model and JSON-encode it?
Do you want the JSON blob in the database aswell?
If not, then you simple define the properties as usual like normal python methods on the model class, and add the code to export them in your serialiser.
If so, then there is a nice field from django-extensions for this
from django_extensions.db.fields.json import JSONField
You just add the field on your model, and it should handle the conversion to and from python / database representations automagically for you.