tags:

views:

295

answers:

2
+1  Q: 

Filter by property

Is it possible to filter by property?

i have a method in my model:

@property
def myproperty(self):
    [..]

and now i want to filter by this property like:

MyModel.objects.filter(myproperty=[..])

is this somehow possible?

+4  A: 

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.

Glenn Maynard
bad luck that this feature is not implemented, would be an interesting extension to at least filter out matching objects _after_ the resultset has been build.
schneck
A: 

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())
Clint
That works to filter it once you have a Python object, but he's asking about Django QuerySet.filter, which constructs SQL queries.
Glenn Maynard
right, but as explained above, i would like to add the property to my database filter. filtering after the query has been done is exactly what i want to avoid.
schneck