As I’ve been working with Django queries, I can’t help but recognize how nice it would be to order queries by a model method, as model methods are meant to act like a field to their respective model. Obviously this cannot be, as the model methods are not actually columns in the model’s table. However, I have also discovered a workaround that could potentially turn into a solution.
Currently, I check if the field to be passed in to order_by is a field name or a model method name. If it is the name of a model method, then I do not include order_by in the query. Instead, I run:
sorted(query_set, key= lambda obj: Model.modelmethod(obj))
I am not sure what the performance hit of this is, but it works great in creating the illusion that the results were ordered by the model method field.
To implement this in to django, there would have to be a similar check to see if the field passed in is a field name or a model method name. It would then need to wait until all of the .order_by() calls are made as it is my understanding that it can be called several times thanks to Django’s lazy querying. Following the same logic, order_by could then perform a basic sort on the queryset as exemplified above as opposed to actually passing any fields in to the query.
I am looking for thoughts and suggestions on this idea and the implementation, as I am currently looking in to how to do so.
class Project(models.Model): due_date = models.DateTimeField() # I want to order a query for projects by priority @property def priority(self): ''' declares the object priority with 1 being highest priority and 3 being least ''' if (self.due_date - timezone.now()).total_seconds() < 0: return 1 elif round(((self.due_date - timezone.now()).days * 24) + ((self.due_date - timezone.now()).seconds / 60 / 60)) < 25: return 2 else: return 3