Django, query filtering from model method


Question

I have these models:

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

Now I want to query Bars that are having active Foo's as such:

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

I am getting error such as

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

How can I achieve this?

1
63
5/29/2015 6:02:29 AM

Accepted Answer

You cannot query against model methods or properties. Either use the criteria within it in the query, or filter in Python using a list comprehension or genex.

33
2/16/2010 10:22:03 PM

You could also use a custom manager. Then you could run something like this:

Bar.objects.foo_active()

And all you have to do is:

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

Check out the docs.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon