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' 

我怎样才能做到这一点?

您无法查询模型方法或属性。 可以使用查询中的标准,也可以使用列表parsing或genex过滤Python。

您也可以使用自定义pipe理器。 那么你可以运行这样的东西:

 Bar.objects.foo_active() 

而你所要做的只是:

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

查看文档 。

我有类似的问题:我使用基于类的视图object_list ,我不得不按模型的方法过滤。 (存储在数据库中的信息是不是一个选项,因为该属性是基于时间,我将不得不创build一个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) 

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

 class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() ... class Category(models.Model): ... open = models.BooleanField(default=True) 

可能是你可以使用简单的filter,这种types的条件。

 Page.objects.filter(category__open=True)