Django save json value for database / model

Im new for django and im trying to save json in the database . The problem is that they managed to get the data in my views, but not sure how to save it in the database . I'm trying to save 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 save data from views to a 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 a better way to do this ...

+5
source share
3 answers

If I clearly understand your question, then your opinion 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() 
+1
source

If you use Postgres, you can save json using JSONField ( read more ), but if not, you need json parsing for the string and save using CharField using json.dumps(data) . To recover data, use json string for dict with json.loads(json_string)

Remember to import json lib: import json

+2
source

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

+2
source

Source: https://habr.com/ru/post/1245454/


All Articles