You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用更优的Django ORM方式查询我关注的用户发布的所有推文

问题原因说明

你之前的Tweets.objects.filter(user__follower = user_idx)写法不通用,是因为对related_name的反向关联逻辑理解有误:

  • UserFollowers中followee_user字段的related_name="followee",代表从User反向查询「哪些人关注了当前用户」的关联关系时使用该名称
  • 你需要查询的是:推文的发布者是你关注的用户,也就是存在一条关注关系,follower_user是你,followee_user是推文的发布者

正确高效的ORM写法

写法1:单句JOIN查询(一次数据库请求,适合中等数据量场景)

my_timeline_tweets = Tweets.objects.filter(
    user__followee__follower_user=user_idx
).distinct()

增加distinct()是为了避免跨表JOIN可能产生的重复推文记录。

写法2:子查询(更适合关注量极大的场景,性能更稳定)

你原来的写法需要把所有关注用户ID拉到Python层循环处理,数据量大时性能很差,改用Django自带的子查询逻辑可以全程在数据库层面操作:

# 这里不会立刻执行查询拉取ID,会作为子查询嵌入到下文的推文查询中
followee_ids = UserFollowers.objects.filter(
    follower_user=user_idx
).values_list('followee_user_id', flat=True)

my_timeline_tweets = Tweets.objects.filter(user_id__in=followee_ids)

两种写法都比你当前的实现性能更高,也不需要手动处理ID列表,你可以根据自己的业务数据规模选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:36:03