I am using Django 1.11 on Python 3, and MySQL 5.7.
Suppose I have a model with a CharField, like so:
class ModelA(models.Model):
ID = models.AutoField(primary_key=True)
a = models.CharField()
And in the shell, I tried doing this:
>>> instance = ModelA(a={'1' : 1})
>>> instance
which gives me a TypeError: __str__ returned non-string (type dict)
But when I do this:
>>> instance.save()
I don't get any error.
If I try:
>>> instance.a
{'1': 1}
But when I try:
>>> ModelA.objects.get(ID=<the ID of the above instance>).a
"{'1': 1}"
Which means that it got stored in the database table as a string.
My question is why does this implicit conversion happen, and why doesn't save() raise an error like __str__() did?
Thanks for your help!
A model instance is just a python object. You can set any attribute to any value.
When you save the instance, all data is converted to the appropriate data types to Django's best ability. For a CharField this means that any truthy value (str(value) is True) is saved in the database
When you save a model, the current values of the field is read, converted to an appropriate data type, and saved to the database.
TypeError: `__str__` returned non-string (type dict)
It's because of before conversion. After saving the data Django will be changed the type to str
so you are not getting an error after saving the instance.
Use JSONField If you want to save the Dict kind of object and make sure you are using Postgres DB.