How to Sort related items in a Django template ?

How to Sort related items in a Django template ?

Asked on October 26, 2018 in Django.
Add Comment


  • 4 Answer(s)

    We need to specify the ordering in the attendee model . For example (assuming our model class is named Attendee):

    class Attendee(models.Model):
        class Meta:
            ordering = ['last_name']
    

     

    Answered on October 26, 2018.
    Add Comment

     

    Try this code, It will work:

    {% for event in eventsCollection %}
        {{ event.location }}
        {% for attendee in event.attendee_set.all|dictsort:"last_name" %}
            {{ attendee.first_name }} {{ attendee.last_name }}
        {% endfor %}
    {% endfor %}
    
    Answered on October 26, 2018.
    Add Comment

    By using regroup we can able to do what we want, but is there is reason we can’t order them the way we want back in the view.

    Answered on October 26, 2018.
    Add Comment

    You need to specify the ordering in the attendee model, like this. For example (assuming your model class is named Attendee):

    class Attendee(models.Model):
        class Meta:
            ordering = ['last_name']

    See the manual for further reference.

    EDIT. Another solution is to add a property to your Event model, that you can access from your template:

    class Event(models.Model):
    # ...
    @property
    def sorted_attendee_set(self):
        return self.attendee_set.order_by('last_name')
    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.