I have two models - a Task
model, and a Worker
model. I have a property on Worker
that counts how many tasks they have completed this month.
class Task(models.Model):
# ...
completed_on = models.DateField()
class Worker(models.Model):
# ...
@property
def completed_this_month(self):
year = datetime.date.today().year
month = datetime.date.today().month
return Task.objects.filter(worker=self,
completed_on__year=year,
completed_on__month=month).count()
I've added this field to the Worker admin, and it displays correctly.
I would like to be able to sort by this field. Is there a way to do this?
Edit: It has been suggested that my question is a duplicate of this question, which uses extra()
. The Django documentation strongly advises against using the extra()
method, and even asks you to file a ticket explaining why you had to use it.
Use this method as a last resort
This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra().