Django filtering requests from a model method

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 request bars that have active Foo as such:

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

I get an error like

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

How can i achieve this?

+57
python django django-models django-orm django-queryset
Feb 16 2018-10-16
source share
5 answers

You cannot request methods or model properties. Either use the criteria inside it in the query, or filter in Python using list comprehension or the gene.

+28
Feb 16 '10 at 22:22
source share

You can also use the user manager. Then you can 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 .

+22
Jan 26 '14 at 12:00
source share

I had a similar problem: I use the object_list view object_list and I had to filter by the model method. (storing information in a database was not a choice, because the property was time-based, and I would have to create a cronjob and / or ... no way)

My answer is ineffective, and I do not know how it will scale according to larger data; but it works:

 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) 
+13
Mar 05 '13 at 13:15
source share

You cannot filter methods, but if the is_active method in Foo checks the attribute on Foo, you can use double-underlined syntax like Bar.objects.filter(foo__is_active_attribute=True)

+10
Feb 16 '10 at 22:24
source share
 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) 

Perhaps you can use a simple filter for this type of condition.

 Page.objects.filter(category__open=True) 
0
Apr 23 '16 at 9:00
source share



All Articles