许多小时以来,我一直在不懈地努力以使此代码正常工作。
我需要使用django的sql查询在json中显示数据库中的帖子和评论结果
下面是我期望的json格式。
[
{"id":"1","title":"post title 1","content":"post content 1.","comment":[{"comment":"comment 1 post 1."},{"comment":"comment 2 post 1."}]},
{"id":"2","title":"post title 2.","content":"post content 2","comment":[{"comment":"comment3 post 2."}]},
{"id":"3","title":"post title 3","content":"post content 3","comment":[]}
]
当我运行下面的代码时,所有的帖子记录都会显示,并且缺少一些注释。 这就是我得到的
[
{"id": 1, "title": "post title 1", "content": "post content 1.", "comment": {"comid": 4, "comment": "coment 4 for post 1"}},
{"id": 2, "title": "post title 2.", "content": "post content 2", "comment": {"comid": 3, "comment": "coment 3 for post 2"}},
{"id": 3, "title": "post title 3", "content": "post content 3", "comment": {"comid": 3, "comment": "coment 3 for post 2"}}
]
我的问题: 数组中缺少一些注释
实例:
1。) ID为1 的帖子在数组中应该有两个评论,但只是希望看到一个附加到该Postid的评论。
2。) ID为3的帖子没有任何评论,但看到其postid附带了评论
我想知道退出循环时该问题是否与标识有关。
有人可以帮我解决问题吗
这是代码
def read(request):
sql = 'SELECT * from crud_posts'
with connection.cursor() as cursor1:
cursor1.execute(sql)
output = cursor1.fetchall()
#print(output[0])
items=[]
for row in output:
postid = row[0]
#Get comments
sql2 = "SELECT * from crud_comment where postid= %s"
pid = (postid)
with connection.cursor() as cursor2:
cursor2.execute(sql2, pid)
output2 = cursor2.fetchall()
items2=[]
for row2 in output2:
comment_array = {'comid':row2[0], 'comment': row2[3]}
#comment_array = items2.append({'comid':row2[0], 'comment': row2[3]})
print('this is comment array:', comment_array)
items.append({'id':row[0], 'title': row[1],'content': row[2], 'comment': comment_array})
jsondata = json.dumps({'items': items})
return HttpResponse(jsondata, content_type='application/json')
这是 models.py
class Posts(models.Model):
title = models.CharField(max_length=40)
content = models.CharField(max_length=400)
def __str__(self):
return self.title + " " + self.content
class Comment(models.Model):
userid = models.IntegerField()
postid = models.IntegerField()
comment = models.CharField(max_length=400)
def __str__(self):
return self.userid + " " + self.postid