Django返回评论Model查询结果为JSON时如何获取关联用户外键字段值
错误原因说明
- 你修改后的
views.py里"commented_by": commented_by写法错误,缺少前缀comment.属于未定义变量,直接触发运行报错 - Django的
serializers.serialize方法仅支持序列化Django模型实例的查询集,你手动拼接的普通字典列表无法用该方法序列化
可用解决方案
方案1:直接用values指定关联字段(最简单)
通过Django ORM双下划线语法直接查询关联用户表的字段,无需额外循环处理:
def load_comments(request, post_id): """Returns the comments to index.js""" try: post = Post.objects.get(pk=post_id) # 需要用户的什么字段就添加对应的双下划线字段即可 comments = list(Comment.objects.filter(post=post).values( "comment", "commented_by__id", "commented_by__username" )) return JsonResponse({"comments": comments}) except Post.DoesNotExist: # 指定捕获异常类型比裸except更安全,同时设置正确的HTTP状态码 return JsonResponse({"error": "Post not found", "status": 404}, status=404)
对应JS取值写法:
b.textContent = comment.commented_by__username + " ";
方案2:手动拼接返回字典(更灵活,推荐)
搭配select_related做连表查询优化,避免N+1查询问题,可自定义返回数据结构:
def load_comments(request, post_id): """Returns the comments to index.js""" try: post = Post.objects.get(pk=post_id) # select_related提前加载关联用户数据,避免循环时重复查询数据库 post_comments = Comment.objects.filter(post=post).select_related("commented_by") comments = [] for comment in post_comments: comments.append({ "comment": comment.comment, "commented_by": { "id": comment.commented_by.id, "username": comment.commented_by.username # 需要其他用户字段直接在这里添加即可 } }) return JsonResponse({"comments": comments}) except Post.DoesNotExist: return JsonResponse({"error": "Post not found", "status": 404}, status=404)
对应JS取值写法:
b.textContent = comment.commented_by.username + " ";
内容的提问来源于stack exchange,提问作者user15440172
相关产品推荐
相关产品推荐

