简体   繁体   中英

Django ORM Multicolumn join

Users of my app are able to block other users so blocked users won't see their blockers anywhere in the app. I have following models

class User(models.Model):
    blocked_users = models.ManyToManyField(
        'self', symmetrical=False, through='Block')


class Block(models.Model):
    class Meta:
        unique_together = ('from_user', 'to_user')

    from_user = models.ForeignKey('User', related_name='blocked')
    to_user = models.ForeignKey('User', related_name='blocked_by')

So now I'm trying to make Django do the following query that will return users who didn't block currently logged in user.

SELECT *
FROM user
LEFT OUTER JOIN block ON (block.from_user_id = user.id AND block.to_user_id = 1)
WHERE block.id is null

where 1 is an id of the currently logged in user.

what about .exclude() ?

User.objects.exclude(blocked_by__to_user__id=request.user.id)

maybe more efficient something like:

User.objects.filter(user__blocked_by__to_user=request.user.id, blocked_by__is_null=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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