[Answer]-Django CBV ordering in list view not working

1👍

✅

First of all, I wouldn’t recommend mixing a SingleObjectMixin and ListView. They are written for two distinct goals and are incompatible in the way they achieve those. You can patch it up like you did, but if you’re not very careful you can still run into a lot of unexpected behaviour, especially when relying on a call to super. You’re actually just trying to create a detail view, so you should subclass DetailView with PointOfInterest as your model.

Now for your sorting problem: you can’t pass arguments to functions in your template, so you’ll have to sort the queryset in your context in the view, or create a function without any (required) arguments. I’d go with the first method, to keep logic for your view in your view code, and to prevent cluttering your model with helper methods. Either way, you’ll have to keep track of which queryset you’re using exactly, as sorting one queryset won’t affect another queryset.

So to go with the context method:

class POIDetail(DetailView):
    model = PointOfInterest

    def get_context_data(self, **kwargs):
        context = super(POIDetail, self).get_context_data(**kwargs)
        context['sorted_event_list'] = self.object.events.order_by('start')
        return context

And in your template, iterate using {% for event in sorted_event_list %}.

Leave a comment