I am imagining. Consider a model called Imagine
from django.db import models
class Imagine(models.Model):
state = models.BooleanField(default=True)
priority = models.IntegerField()
@property
def extra(self):
return 100 * self.priority
Is it possible to construct a query as such:?
Imagine.objects.filter(extra=200)
I know that extra
is not a field. Like I said, I am just imagining … because I often wish it is possible to filter a query with the results of an associated model atttribute or function. Maybe there is a similar way to do it. Who knows?
Not as you’ve written it, no.
Keep in mind where things are being done.
An ORM expression results in an SQL query being sent to the database for the database to execute.
On the other hand, the function you are trying to reference in Python code and doesn’t exist in the database.
If you wanted something similar to this, you would need to use the annotate
function with a database formula expression to calculate this value.
Sometimes I forget that I am actually constructing SQL queries with those django expressions. Thanks for the reorientation.
that prompted a workaround
from django.db import models
class Imagine(models.Model):
state = models.BooleanField(default=True)
priority = models.IntegerField()
extra = models.IntegerField()
def update_extra(self):
self.extra = 100 * self.priority
self.save()
So I compute the filter ahead and store the value as a state (extra
) in a field. A bit crude but within my capacity at the moment. I can’t think of an easy way to get what I want with database functions. I am still a django student eventually. The real scenario is more complex than the above example.