问题描述
我有 2 个模型:
关注者有 1000 万次查询
class Follower(models.Model):
identifier = models.BigIntegerField(
_("identifier"),unique=True,null=False,blank=False)
username = models.CharField(
_("username"),max_length=250,null=True,blank=True)
Actions 有 500 万次查询
class ActionModel(models.Model):
target = models.ForeignKey(Follower,verbose_name=_("Target"),on_delete=models.CASCADE) # username
is_followed_back = models.BooleanField(_("Followed Back"),blank=True) # is target followed back
user = models.ForeignKey(
settings.AUTH_USER_MODEL,on_delete=models.CASCADE,editable=False
) # django user that performed the action
每次我进入 Follower 的管理面板时,我想计算每个用户每个关注者的操作数,并且 follow_back 字段为 True :
def get_queryset(self,request):
...
actionmodel__user = Q(actionmodel__user=request.user)
qs = qs.annotate(
been_followed_count=Count('actionmodel',filter=actionmodel__user,distinct=True)
).annotate(
follow_back_count=Count(
'actionmodel',filter=(actionmodel__user & Q(actionmodel__is_followed_back=True)),distinct=True
)
)
它可以工作,但速度很慢!
我猜它会过滤它所操作的 1000 万粉丝中的每一个……所以它运行了 10M X 5M 次? 什么是替代方案?我无法在 Follower 模型上存储“been_followed_count”和“follow_back_count”,因为它对所有 django 用户都是通用的,所以我可以以某种方式存储这些值,或者每个 get_queryset 重新计算它吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)