Django saving json value to database/model

前端 未结 5 645
清歌不尽
清歌不尽 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:09

    Assuming a model of:

    class User(models.Model):
      name = models.CharField()
      phone_number = models.CharField()
    

    Sending json of {"name":"Test User", "phone_number":"123-456-7890"}

    In the view you could do the following to save it to the database.

    def SaveUser(request):
      body_unicode = request.body.decode('utf-8')
      body = json.loads(body_unicode)
      u = User(**body)
      u.save()
      return JsonResponse({"result": "OK"})
    
    0 讨论(0)
  • 2020-12-28 20:11

    If you're using Postgres, you can store json with JSONField (read more), but if not, you need parse json to string and save with CharField/TextField using json.dumps(data). To recovery data, use json string to dict with json.loads(json_string)

    Remember to import json lib: import json

    0 讨论(0)
  • 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',
             }],
         },
    })
    
    0 讨论(0)
  • 2020-12-28 20:24

    If I understand your question clearly then Your view should be something like.

    def add_comments(request):
        if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE']:
            print 'hi'
            data = json.loads(request.body)
            comment = data.get('comment', None)
            id = data.get('id', None)
            title = data.get('title', None) 
    
            post = Post.objects.get(id = id)
            com = Comment()
            com. comments = comment
            com.title = post
            com.save()
    
    0 讨论(0)
  • 2020-12-28 20:24

    If you want to store the intact JSON, try using the django-jsonfield project: https://github.com/dmkoch/django-jsonfield

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