Django将json值保存到数据库/模型 [英] Django saving json value to database/model
本文介绍了Django将json值保存到数据库/模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是django的新手,并且正在尝试将 json保存到数据库。问题在于无法获取我视图中的数据,但不确定如何将其保存在数据库中。我正在尝试保存评论
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
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)
序列化器.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...
推荐答案
如果我清楚地理解了您的问题,那么
您的视图应该类似于。
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()
这篇关于Django将json值保存到数据库/模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文