Python Django 将 json 值保存到数据库/模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36123877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django saving json value to database/model
提问by Coeus
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
我是 Django 新手,我正在尝试将json保存到数据库。问题是我能够在我的视图中获取数据,但不确定如何将其保存在数据库中。我正在尝试保存评论
models.py
模型.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
序列化程序.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
查看.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...
提前致谢........请让我知道是否有更好的方法来做到这一点...
采纳答案by burning
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()
回答by Guilherme IA
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
using json.dumps(data)
. To recovery data, use json string to dict with json.loads(json_string)
如果您使用 Postgres,您可以使用JSONField
(阅读更多)存储 json ,但如果不是,您需要将 json 解析为字符串并使用CharField
using保存json.dumps(data)
。要恢复数据,请使用 json 字符串来 dictjson.loads(json_string)
Remember to import json lib: import json
记得导入json lib: import json
回答by Josh O'Bryan
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"}
发送 {"name":"Test User", "phone_number":"123-456-7890"} 的 json
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"})
回答by rprasad
If you want to store the intact JSON, try using the django-jsonfield project: https://github.com/dmkoch/django-jsonfield
如果要存储完整的 JSON,请尝试使用 django-jsonfield 项目:https: //github.com/dmkoch/django-jsonfield