Django-filter - can it handle @property attributes?

Hi, I have a person model that contains date_of_birth and also a calculated @property ‘age’.
Is it possible to use the age property in django-filter? I’ve established that I cannot simply add age to the Meta fields TypeError: 'Meta.fields' must not contain non-model field names: age

and defining age as follows doesn’t work either…

age = filters.NumberFilter(field_name=person__age)
NameError: name 'person__age' is not defined

Any suggestions? Thanks

hi, the answer is no. :slight_smile:

What you have to do in this case is use annotations (look it up on the official docs).

1 Like

To add to the previous response - keep in mind that the ORM functions by building an SQL query that is sent to the database to be executed. Functions and properties in your Django models exist in Django, not in the database, so those features are not available to the database when making queries.

Having said that, PostgreSQL (and probably all the other supported databases) have a sufficiently robust query language such that most expressions you would create as properties in Django could be written as part of a query. That’s where the annotations and Query expressions com into play.