Python Django相关模型字段查询(共同好友)

Python Django相关模型字段查询(共同好友),python,sql,django,django-rest-framework,Python,Sql,Django,Django Rest Framework,我有一个友谊模型: class Friendship(models.Model): user = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="friend1", null=True, blank=True) other_user = models.ForeignKey( Account, on_delete=models.CASCADE, related_

我有一个友谊模型:


class Friendship(models.Model):
    user = models.ForeignKey(
        Account, on_delete=models.CASCADE, related_name="friend1", null=True, blank=True)
    other_user = models.ForeignKey(
        Account, on_delete=models.CASCADE, related_name="friend2", null=True, blank=True)
    date_created = models.DateTimeField(auto_now=True)

    objects = FriendshipManager()

    class Meta:
        verbose_name = "friendship"
        verbose_name_plural = "friendships"
        unique_together = ("user", "other_user")

    def __str__(self):
        return f'{self.user} is friends with {self.other_user}.'

此函数用于返回两个帐户的共同好友的所有用户


def mutual_friends(self, account1, account2):
        mutual_friends = Account.objects.filter(
            Q(friend2__user=account1) & Q(friend2__user=account2))
        return mutual_friends

基于我对查询api如何工作的(有限的)理解,我认为这应该返回与友谊表有“friend2”关系的所有用户,其中“friend1”用户是account1或account2。我仍然习惯于询问django,所以如果有人能让我知道我做错了什么,那就太好了


谢谢

我觉得你的模型设计不对。现在,您可以将任何
帐户
实例设置为
用户
其他用户
,并且由于它们都引用相同的模型(
帐户
),在从数据库进行任何检索时,您需要考虑这两个字段

IMO更好的设计是在
帐户
模型中使用
ManyToManyField
(多对多关系),因为一个帐户可以有多个其他帐户作为朋友,反之亦然。因此:

class Account(models.Model):
    ...
    friends = models.ManyToManyField('self')
    ...
现在,您可以添加朋友,例如:

account_foo.friends.add(account_bar, account_spam)
account.*
account
实例

您可以获得
account\u foo
的所有好友,如:

account_foo.friends.all()
查看以获取各种数据集成和查询示例


现在,要查找共同的朋友,例如
account\u-foo
account\u-bar
,您可以首先获取
account\u-foo
的所有朋友,然后查看他们中的哪些人也是
account\u-bar
的朋友:

friends_with_foo = account_foo.friends.values_list('pk', flat=True)
mutual_friends_of_foo_bar = account_bar.friends.filter(pk__in=friends_with_foo)

这是一个双向系统,当用户添加一个朋友时,它会创建两个朋友,a是b的朋友,b是b的朋友a@pererasys这正是上面的
ManyToManyField
所做的。我还有更多关于我想储存的友谊的信息,根据你的建议,我可以使用一个直通模式,但这比我现在的工作有什么优势呢implementation@pererasys正如我所说,当您在模型中添加一个帐户时,您总是将其添加为
user
other\u user
还是两者都添加
ForeignKey
是多对一的,我想你没有考虑到这一点。当用户a将用户B添加为好友时,会创建两个好友。第一:用户=A,其他用户=B;第二个:user=B,other_user=A,这就是为什么我可以通过查询Q(friend2_uuser=account)来获取所有friends账户的原因