How to store a dictionary in a Django database model's field

前端 未结 9 1300
不思量自难忘°
不思量自难忘° 2020-12-03 20:31

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         


        
相关标签:
9条回答
  • 2020-12-03 21:27

    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.

    0 讨论(0)
  • 2020-12-03 21:30

    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

    0 讨论(0)
  • 2020-12-03 21:34

    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.

    0 讨论(0)
提交回复
热议问题