在另一个查询中排除查询结果

时间:2014-01-29 09:28:13

标签: django python-2.7

我想要做的就是,我想列出所有没有阻止我的人。在表格 Blocked 中有两列名称 who whose 。在 whose 列中,我存储了我阻止的人的ID,并在 who 列中存储了我的ID。现在我想这样做,当被阻止的人点击 我网页上的查看人按钮,他看不到阻止他的人的个人资料。

当我执行此查询时 blocked_list = Blocked.objects.filter(whose = user_id) 。现在我得到了阻止我的人员名单。现在,我想从此查询 total_profiles = persons.objects.all().exclude(blocked_list) 中排除所有此人。我怎么能这样做。

models.py

class persons(models.Model):
    full_name = models.CharField(max_length=200)


class blocked(models.Model):
    who = models.ForeignKey(persons)
    whose = models.IntegerField(null=True) 

views.py

def blocked(request): 
    blocked_list = Blocked.objects.filter(whose = user_id) 
    total_profiles = persons.objects.all().exclude(blocked_list)
    return render_to_response('profiles/view_all.html', {'total_profiles':total_profiles,'}, context_instance=RequestContext(request),) 

如果问题不正确,请更正。

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

total_profiles = persons.objects.all().exclude(id__in = blocked_list.values_list('id', flat=True))

它未经测试,但改编自this answer

一些注意事项:

  • 如果persons有默认管理员,则可以省略all()
  • whose没有索引,因此当数据集变大时,它会变慢。您可以使用ForeignKey字段代替IntegerField
  • 常见的惯例是大写类名并以单数形式写出模型名称,即Person而不是persons