I have the following code in my model, which determines if an Entry is billable:
class Entry(models.Model):
[ .. ]
@property
def is_billable(self):
return self.tags.filter(billable=False).count() == 0
Entry has an FK to Project. When determining the remaining budget on a Project, I loop through all the entries, and check if is_billable returns True:
@property
def remaining_budget(self):
[ .. ]
for entry in self.entry_set.all():
if entry.is_billable:
remaining_budget -= entry.minutes
Which is kind of heavy for the database, because it’ll fire a query for each Entry. I’m looking for a way to optimize this, tips and hints are welcome.
If you need to get rid of the count query then why not:
is_billablefield to yourEntrymodelis_billable == Trueis added, then set it True / if a tag is removed and no tags withis_billable == Trueremain, then set it False, etc)Of course if your data can be changed through other apps or manually, this method should not be preferred.