Django ORM多列连接

时间:2017-10-13 12:35:21

标签: python django django-orm

我的应用的用户可以阻止其他用户,因此被阻止的用户不会在应用中的任何位置看到他们的拦截器。我有以下模型

left: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    justifyContent: 'center'
  },
  right: {
    position: 'absolute',
    right: 30, <- I set right from 30 to 0 and I could see the button (But it shows just the part of the botton. Can I do it better?
    top: 0,
    bottom: 0,
    justifyContent: 'center'
  },
  title: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',

所以现在我正在尝试让Django执行以下查询,该查询将返回未阻止当前登录用户的用户。

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')

其中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 是当前登录用户的ID。

1 个答案:

答案 0 :(得分:0)

.exclude()怎么办?

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

可能更有效:

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