Django,来自模型方法的查询过滤

我有这些模型:

def Foo(Models.model):
size = models.IntegerField()
# other fields


def is_active(self):
if check_condition:
return True
else:
return False


def Bar(Models.model):
foo = models.ForeignKey("Foo")
# other fields

现在我想查询一下那些拥有活跃 Foo 的酒吧:

Bar.objects.filter(foo.is_active())

我得到了错误,如

SyntaxError at /
('non-keyword arg after keyword arg'

我怎么才能做到呢?

52286 次浏览

不能对模型方法或属性进行查询。要么在查询中使用其中的条件,要么在 Python 中使用列表内涵或 genex 进行筛选。

您不能过滤方法,但是如果 Foo 上的 is _ active 方法检查 Foo 上的属性,您可以使用双下划线语法,如 Bar.objects.filter(foo__is_active_attribute=True)

我也有类似的问题: 我使用的是基于类的视图 object_list,我必须通过模型的方法进行过滤。(在数据库中存储信息不是一个选项,因为属性是基于时间的,我必须创建一个 cronjob 和/或... 不可能)

我的回答是无效的,我不知道它将如何在更大的数据上扩展; 但是,它是有效的:

q = Model.objects.filter(...)...
# here is the trick
q_ids = [o.id for o in q if o.method()]
q = q.filter(id__in=q_ids)

你也可以使用一个定制管理器,然后你可以运行这样的程序:

Bar.objects.foo_active()

你要做的就是:

class BarManager(models.Manager):
def foo_active(self):
# use your method to filter results
return you_custom_queryset

看看 医生