I'm looking to sort the results from query sets for django by a certain structure of names and related objects. Order_by() is not viable, since it doesn't accept methods. Making an extra column that hardcodes the name I want isn't practical, and is a workaround for lacking functionality.
I thought to use a custom manager to do this, but I'm having trouble since sorted() always returns a list, and django wants the object to stay as a QuerySet. So, my question is, is there any decent way to use sorted() on a custom class (where the class is basically a list with some extra methods) and get it to remain that custom class? This is actually pretty general, and probably has uses outside of just QuerySets as well.
class ClientManager(models.Manager):
def get_query_set(self):
set = super(ClientManager,self).get_query_set()
return sorted(set, key=lambda a: a.fullName())
As a couple points (and responses to some of the comments here):
- Documentation on annotate seems to imply that it's limited to aggregation functions. I'd like this to run on a method instead.
- Caching the value is too much of a workaround for what I'd like to do. Even if it is the best solution from some perspectives, it's not dynamic enough for my taste, and seems to violate DRY in my opinion.
I've seen lots of posts on this subject, it may be that a lack of real sorting capabilities is a shortcoming of django. This sorting is necessary, so that I can make my way through the django admin for tons of data, sorted in a human-understandable way.
Added Question
It might be a viable solution if I could turn a list of objects into a QuerySet of objects. Anyone know if this is possible? Specifically, transform it into a <class 'django.db.models.query.QuerySet'>
object.