Django查询指定ForumTopic下ForumMessage并关联过滤后ForumMessageVote的方法
实现方案
方案1:使用annotate + 子查询(推荐,性能最优)
仅需一次查询即可将指定用户的投票值直接附加到消息字段上,适合只需要投票数值的场景。
from django.db.models import OuterRef, Subquery, Coalesce, Value # 替换为你实际拿到的指定话题、指定用户对象 target_topic = ForumTopic.objects.get(id=话题ID) target_user = User.objects.get(id=用户ID) # 构造子查询:匹配当前消息和指定用户的投票记录 vote_subquery = ForumMessageVote.objects.filter( user=target_user, message=OuterRef('pk') ).values('vote')[:1] # 主查询:查询话题下所有消息,同时附加上用户投票值 messages = ForumMessage.objects.filter( topic=target_topic ).annotate( # Coalesce用于处理未投票的场景,默认返回0,不需要可以删掉直接用Subquery(vote_subquery) user_vote=Coalesce(Subquery(vote_subquery), Value(0)) )
访问方式:直接通过message.user_vote即可拿到当前用户对这条消息的投票值,未投票时返回0。
方案2:使用prefetch_related预过滤关联投票
总共执行2次查询,适合需要拿到完整ForumMessageVote对象的场景。
from django.db.models import Prefetch # 替换为你实际拿到的指定话题、指定用户对象 target_topic = ForumTopic.objects.get(id=话题ID) target_user = User.objects.get(id=用户ID) # 配置预取规则:只拉取指定用户的投票记录 prefetch_votes = Prefetch( 'forummessagevote_set', queryset=ForumMessageVote.objects.filter(user=target_user), to_attr='user_vote' ) # 主查询 messages = ForumMessage.objects.filter( topic=target_topic ).prefetch_related(prefetch_votes)
访问方式:message.user_vote是一个列表,如果用户投过票则列表内包含对应的投票对象,否则为空列表。
内容的提问来源于stack exchange,提问作者cin
相关产品推荐
相关产品推荐

