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

前端 未结 9 1391
不思量自难忘°
不思量自难忘° 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.

提交回复
热议问题