【问题标题】:Django query users that like each otherDjango 查询互相喜欢的用户
【发布时间】:2019-10-01 00:27:17
【问题描述】:

我有一个看起来像这样的 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))

【问题讨论】:

  • 据我了解,我认为您正在尝试分两部分进行查询:首先获取已投票为 True 的所有记录,然后找到所有用户选民投票正确。 如果用户(投票者投票)也为用户(投票者)投票,则显示记录。 是真的吗?如果是,那么您可以首先获取选民投票为真的用户。然后为每个被选民投票为真的用户检查第二个条件。

标签: python mysql sql django orm


【解决方案1】:

考虑 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))

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

【讨论】:

    【解决方案2】:

    我觉得应该是这样的:

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

    意思是,它会返回所有投票者是用户自己或他是其他人投票给他的用户的所有匹配项。

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 2013-01-03
      • 2014-03-30
      • 1970-01-01
      • 2012-12-23
      • 2012-09-18
      相关资源
      最近更新 更多