Coe*_*eus 13 python django json
我是django的新手,我试图将json保存到数据库.问题是,我能够在我的视图中获取数据,但不知道如何将数据保存在数据库中.我试图保存评论
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)
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
请帮我将数据从视图保存到数据库
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
Run Code Online (Sandbox Code Playgroud)
在此先感谢........如果有更好的方法,请告诉我...
假设一个模型:
class User(models.Model):
name = models.CharField()
phone_number = models.CharField()
Run Code Online (Sandbox Code Playgroud)
发送 {"name":"Test User", "phone_number":"123-456-7890"} 的 json
在视图中,您可以执行以下操作将其保存到数据库中。
def SaveUser(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
u = User(**body)
u.save()
return JsonResponse({"result": "OK"})
Run Code Online (Sandbox Code Playgroud)
如果我清楚地理解你的问题那么你的观点应该是这样的。
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')
id = data.get('id')
title = data.get('title')
post = Post.objects.get(id = id)
com = Comment()
com. comments = comment
com.title = post
com.save()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16948 次 |
| 最近记录: |