I need to save a dictionary in a model\'s field. How do I do that?
For example I have this code:
def create_random_bill(self):
name_chars = re.co
according to Django doc you can use :
from django.contrib.postgres.fields import JSONField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = JSONField()
def __str__(self):
return self.name
and create with this :
Dog.objects.create(name='Rufus', data={
'breed': 'labrador',
'owner': {
'name': 'Bob',
'other_pets': [{
'name': 'Fishy',
}],
},
})
I hope this could help you.
If using PostGres you can store it in natively supported JSON field: https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#jsonfield
Otherwise I'd recommend @ramiro answer with 3rd party lib https://stackoverflow.com/a/16437627/803174
I think that I would create the field as models.CharField() and then encode the dictionary as a JSON string and save that string into the database. Then you can decode the JSON string back into a dictionary when you read it out.