我有一个由另一个用户录制的喜欢的模型:
class Like(models.Model):
owner = models.ForeignKey(User, related_name="like_owner")
likee = models.ForeignKey(User, related_name="like_likee")
我想知道最好的方法来获得至少有1个相似的用户的输出。现在我有一个解决方案,我基本上遍历每个用户的“like_owner”列表,计算它们也被命名为匹配的次数,但这似乎效率低下。
知道如何通过巧妙的聚合来解决这个问题吗?
编辑以添加我的(错误)代码:
users #list of preselected users I wish to find mutual matches for
for u in users:
#check if user has requested contacts and is also at least 1 requested contact to reduce costly queries
if u.like_owner.count() > 0 and u.like_likee.count() > 0:
all = u.like_owner.all()
for r in all:
m = Like.objects.filter(r.likee=u, owner=r.likee).count()
print m
答案 0 :(得分:0)
是的,有更好的解决方案。试试gt
或gte
User.objects.filter(like__likee__gte=1)
答案 1 :(得分:0)
对于Django queryset我在想,但如果你对原始查询没问题。这可能是最好的方式。
SELECT DISTINCT * FROM (select fv1.owner_id as ui1, fv2.owner_id as ui2 from Like fv1 LEFT JOIN Like fv2 ON fv1.likee_id = fv2.likee_id where fv1.owner_id != fv2.owner_id) as a