简体   繁体   English

Django ORM查询用户的朋友

[英]Django ORM query for friends of a user

I am having trouble getting a Django ORM query to work correctly. 我无法让Django ORM查询正常工作。 I have this Friendship model: 我有这个友谊模型:

class Friendship(models.Model):
    user1 = models.ForeignKey(User, related_name='friendships1')
    user2 = models.ForeignKey(User, related_name='friendships2')
    class Meta:
        unique_together = ('user1', 'user2',)

To find the friends for a given user, we have to check user1 and user2 because we can never be sure what side of the relationship they will be on. 要查找给定用户的朋友,我们必须检查user1和user2,因为我们永远无法确定他们将在哪个方面建立关系。 So, to get all friends for a given user, I use the following query: 因此,为了获得给定用户的所有朋友,我使用以下查询:

user = request.user
User.objects.filter(
    Q(friendships1__user2=user, friendships1__status__in=statuses) |
    Q(friendships2__user1=user, friendships2__status__in=statuses)
)

This seems to me like it should work, but it does not. 在我看来,这似乎应该有效,但事实并非如此。 It gives me duplicates. 它给了我重复。 Here is the SQL that it generates: 这是它生成的SQL:

SELECT auth_user.*
FROM auth_user
LEFT OUTER JOIN profile_friendship ON (auth_user.id = profile_friendship.user1_id)
LEFT OUTER JOIN profile_friendship T4 ON (auth_user.id = T4.user2_id)
WHERE (
    (profile_friendship.status IN ('Accepted') AND profile_friendship.user2_id = 1 )
    OR (T4.user1_id = 1 AND T4.status IN ('Accepted'))
);

Here is the SQL that I want, which produces correct results: 这是我想要的SQL,它产生了正确的结果:

SELECT f1.id as f1id, f2.id AS f2id, u.*
FROM auth_user u
LEFT OUTER JOIN profile_friendship f1 ON (u.id = f1.user1_id AND f1.user2_id = 1 AND f1.status IN ('Accepted'))
LEFT OUTER JOIN profile_friendship f2 ON (u.id = f2.user2_id AND f2.user1_id = 1 AND f2.status IN ('Accepted'))
WHERE f1.id IS NOT NULL OR f2.id IS NOT NULL

I know I can do this in a raw query, but then I don't think I'll be able to chain. 我知道我可以在原始查询中执行此操作,但后来我认为我无法链接。 Is there a nice clean way to do this without going raw? 有没有一个很好的清洁方式来做到这一点,而不是生吃?

Simple solution: 简单方案:

user = request.user
User.objects.filter(
    Q(friendships1__user2=user, friendships1__status__in=statuses) |
    Q(friendships2__user1=user, friendships2__status__in=statuses)
).distinct()

Anyone know any drawback? 有人知道任何缺点吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM