Django saving json value to database/model

前端 未结 5 644
清歌不尽
清歌不尽 2020-12-28 19:30

Im new to django and im trying to save json to database. The problem is that im able to get data the data in my views but not sure how to save it in

5条回答
  •  有刺的猬
    2020-12-28 20:21

    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
    

    then create with this :

    Dog.objects.create(name='Rufus', data={
         'breed': 'labrador',
         'owner': {
             'name': 'Bob',
             'other_pets': [{
                 'name': 'Fishy',
             }],
         },
    })
    

提交回复
热议问题