gpt4 book ai didi

python - Django 查询互相喜欢的用户

转载 作者:行者123 更新时间:2023-11-29 16:01:51 27 4
gpt4 key购买 nike

我有一个如下所示的 Django 模型:

class Matches(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
voter = models.ForeignKey(User, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)

我正在尝试使用 django 的 ORM 编写查询,但卡住了。给定一个用户(假设是 user_1),我想返回 user_1 对另一个用户(假设是 user_2)投了 True 票并且 user_2 对 user_1 投了 True 票的所有行。

我想我可能需要使用 Django 的 Q function但不确定。这是我得到的:

class User:
def calculate_matches(self):
return Matches.objects.filter(Q(voter=self, vote=True) & Q(user=self, vote=True))

最佳答案

考虑 ID 为 1 的用户投票给 ID 为 2 的用户投票,反之亦然。那么相关的sql就是

SELECT "users_matches"."id", "users_matches"."user_id", "users_matches"."voter_id", "users_matches"."vote" FROM "users_matches" WHERE ("users_matches"."vote" = True AND "users_matches"."voter_id" = 1 AND "users_matches"."user_id" = 2 AND "users_matches"."vote" = True)

你尝试过的 Django ORM 看起来没问题。

Matches.objects.filter(Q(voter=1, vote=True) & Q(user=2, vote=True))

如果您没有获得准确的输出,请提供更多信息,并在示例输出中提及您期望的输出。

关于python - Django 查询互相喜欢的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122594/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com