You need to enable JavaScript to run this app. Django中如何拓展已关注用户评论的查询集以关联用户详情字段
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何拓展已关注用户评论的查询集以关联用户详情字段

实现方法

基础取数逻辑

你当前的查询本身就关联了评论对应的作者(author外键关联内置User模型),每一条返回的Review实例都可以直接通过点语法访问User模型的任意字段,不需要对filter逻辑做额外修改。
比如直接遍历取数:

target_reviews = Review.objects.filter(author__following__follower=user)
for review in target_reviews:
    # 直接读取用户表字段
    author_name = f"{review.author.first_name} {review.author.last_name}"

默认的查询结果只是没有平铺展示关联User的字段,并非无法获取。

性能优化写法

直接使用基础查询会触发N+1问题:每遍历一条评论就单独发起一次查询获取关联的作者用户数据。可以通过select_related预加载关联对象,把评论和作者数据合并为单条SQL查询:

Review.objects.filter(author__following__follower=user).select_related("author")

这个写法不会改变返回的Review实例结构,只是提前加载关联的作者数据,后续访问review.author的任意字段时不会产生额外SQL开销。

直接平铺字段的写法

如果需要拿到扁平的结构化数据(比如直接给接口做序列化返回),不需要构造完整的Model实例,可以通过values()直接指定要返回的字段,把需要的User模型字段加入查询:

Review.objects.filter(
    author__following__follower=user
).values(
    "id",
    "text_content",
    "movie_rating",
    "author__id",
    "author__username",
    "author__first_name",
    "author__last_name"
)

如果觉得author__xxx的字段名称冗余,可以结合F()表达式给字段重命名:

from django.db.models import F

Review.objects.filter(
    author__following__follower=user
).annotate(
    author_username=F("author__username"),
    author_first_name=F("author__first_name"),
    author_last_name=F("author__last_name")
).values(
    "id",
    "text_content",
    "movie_rating",
    "author_username",
    "author_first_name",
    "author_last_name"
)

你当前编写的过滤逻辑本身是正确的:关联路径为 Review.author -> 该用户的关注关系(Follow模型中following字段指向的User) -> Follow记录的follower为传入的指定用户,完全匹配“获取我关注的人发布的所有评论”的需求。

内容的提问来源于stack exchange,提问作者someone12321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 15:54:06