Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django saving json value to database/model

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 database. Im trying to save the comments

models.py

class Post(models.Model):
    title=models.CharField(max_length=200)
    description=models.TextField(max_length=10000)
    pub_date=models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=40, unique=True)

    def __unicode__(self):
        return self.title


class Comment(models.Model):
    title=models.ForeignKey(Post)
    comments=models.CharField(max_length=200)

    def __unicode__(self):
        return '%s' % (self.title)

serializer.py

class CommentSerializer(serializers.ModelSerializer):
    id = serializers.CharField(source="title.id", read_only=True)
    title = serializers.CharField(source="title.title", read_only=True)

class Meta:
    model = Comment
    fields = ('id','title','comments')


class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id','title','description','pub_date')

Please help me saving the data from views to database

view.py

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) 
        ....................# not sure how to save to database
       pass

Thanks in advance........Please let me know if there is any better way to do it...

like image 292
Coeus Avatar asked Mar 21 '16 05:03

Coeus


People also ask

How does Django store JSON data in database?

JSONField() came out. Prior to that you'd be using a TEXT field to store JSON. MySQL introduced a JSON type in version 5.7 but Django doesn't support it out of the box as of 2.1. Django requires you to implement JSON storage in a TextField (MySQL type longtext) and leave it at that.

How does Django save data to database?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is Save () in Django?

save() , django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost.

Can Django return JSON?

Django provides a built-in class JsonResponse that makes returning JSON easy. By default, the JsonResponse class sets a Content-Type header of application/json.


2 Answers

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

like image 59
Guilherme IA Avatar answered Sep 18 '22 13:09

Guilherme IA


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"})
like image 42
Josh O'Bryan Avatar answered Sep 17 '22 13:09

Josh O'Bryan