[Answered ]-Does Django Have a Way to Auto-Sort Model Fields?

2👍

The way that I’d look at doing this is through a custom QuerySet. In your model, you can define the class QuerySet and add your sorting there. In order to maintain all the logic in the model object, I’d also move the contents of get_my_partylines into the QuerySet, too.

## This class is used to replicate QuerySet methods into a manager.
## This way:  Partyline.objects.for_user(foo) works the same as
## Partyline.objects.filter(date=today).for_user(foo)
class CustomQuerySetManager(models.Manager):
    def get_query_set(self):
        return self.model.QuerySet(self.model)
    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)


class Partyline(models.Model):
    ## Define fields, blah blah.
    objects = CustomQuerySetManager()
    class QuerySet(QuerySet):
        def sort_for_request(self, request):
            sort_field = request.REQUEST.get('sortby', 'did').strip()
            reverse_order = False
            if sort_field.startswith('-'):
                search = sort_field[1:]
            else:
                search = sort_field
                reverse_order = True

            # Check to see if the sort term is valid.
            if not (search in Partyline._meta.get_all_field_names()):
                sort_field = 'did'

            partylines = self.all().order_by(sort_field)
            if reverse_order:
                partylines.reverse()
            return partylines
        def for_user(self, user):
            if is_user_type(request.user, ['admin']):
                return self.all()
            else:
                ## Code from get_my_partylines goes here.
                return self.all() ## Temporary.

views.py:

def list_partylines(request):
    """
    List all `Partyline`s that we own.
    """
    partylines = Partylines.objects.for_user(request.user).sort_for_request(request)

0👍

There’s a great example of how this is done in a generic way in django.contrib.admin.views.main.ChangeList although that does much more than sorting you can browse it’s code for some hints and ideas. You may also want to look at django.contrib.admin.options.ModelAdmin the changelist method in particular to get more context.

👤Vasil

Leave a comment