Filter by property


Is it possible to filter a Django queryset by model property?

i have a method in my model:

def myproperty(self):

and now i want to filter by this property like:


is this somehow possible?

12/7/2018 9:10:32 PM

Accepted Answer

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

7/30/2009 9:09:45 AM

I might be misunderstanding your original question, but there is a filter builtin in python.

filtered = filter(myproperty, MyModel.objects)

But it's better to use a list comprehension:

filtered = [x for x in MyModel.objects if x.myproperty()]

or even better, a generator expression:

filtered = (x for x in MyModel.objects if x.myproperty())

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