Python 将django模型查询作为json响应传递
我在一个社交网络上工作。我想加载每个帖子的评论,因此我向服务器发出一个API调用,以获取所需帖子的所有评论。该准则将使一切变得清晰: url.pyPython 将django模型查询作为json响应传递,python,django,Python,Django,我在一个社交网络上工作。我想加载每个帖子的评论,因此我向服务器发出一个API调用,以获取所需帖子的所有评论。该准则将使一切变得清晰: url.py path("comments/<int:post_id>", views.load_comments) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='com
path("comments/<int:post_id>", views.load_comments)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=128)
def load_comments(request, post_id):
"""Returns the comments to index.js"""
try:
# Filter comments returned based on post id
post = Post.objects.get(pk=post_id)
comments = list(Comment.objects.filter(post=post).values())
return JsonResponse({"comments": comments})
except:
return JsonResponse({"error": "Post not found", "status": 404})
视图.py
path("comments/<int:post_id>", views.load_comments)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=128)
def load_comments(request, post_id):
"""Returns the comments to index.js"""
try:
# Filter comments returned based on post id
post = Post.objects.get(pk=post_id)
comments = list(Comment.objects.filter(post=post).values())
return JsonResponse({"comments": comments})
except:
return JsonResponse({"error": "Post not found", "status": 404})
index.js
fetch(`/comments/${post_id}`)
.then(res => res.json())
.then(res => {
// Appoints the number of comments in the Modal title
document.querySelector("#exampleModalLongTitle").textContent = `${res.comments.length} Comments`;
res.comments.forEach(comment => {
modal_body = document.querySelector(".modal-body")
b = document.createElement("b");
span = document.createElement("span");
br = document.createElement("br");
span.classList.add("gray")
b.textContent = comment.commented_by_id + " ";
span.textContent = comment.comment;
modal_body.appendChild(b);
modal_body.appendChild(span);
modal_body.appendChild(br);
})
我可以使用js
中的comment.comment
获取注释值。但是,当我将注释
对象转换为列表。值
时会出现问题,因此现在我无法获取发布注释的用户(注释者
)
如需获得注释
和注释
值的任何帮助,我们将不胜感激。
我还尝试了视图。py:
def load_comments(request, post_id):
"""Returns the comments to index.js"""
try:
# Filter comments returned based on post id
post = Post.objects.get(pk=post_id)
post_comments = Comment.objects.filter(post=post)
comments = []
for comment in post_comments:
comments.append({
"comment": comment.comment,
"commented_by": commented_by,
})
comments = serializers.serialize('json', comments)
return HttpResponse(comments, content_type='application/json')
except:
return JsonResponse({"error": "Post not found", "status": 404})
但是,当我尝试此操作时,它会输出错误。1-您应该使用django_Rest_框架,因为使用api和显示相关字段非常容易 2-使用
Post.objects.get(id=Post\u id)
而不是pk
或者您应该跳过这一步,直接过滤注释依赖于post id,如Comment.objects.all().filter(post\u id=post\u id)
在Django中,ForeignKey字段的values()函数默认情况下返回相关对象的id,其中包含通过在字段名称后面加上“\u id”形成的键。因此,在您的情况下,您的用户ID位于键下,由\u ID
注释
如果“失去获取发表评论的用户的能力”是指其他用户信息,如用户名,则可以将需要的字段传递给values()函数
comments = list(Comment.objects
.filter(post=post)
.values("comment",
"commented_by__username"
))
将给出一个带有注释文本和用户名的dict(假设您的用户模型中有一个
username
字段)。这就是我所缺少的。感谢您的慷慨帮助。