Sorting related items in a Django template

霸气de小男生 提交于 2019-11-27 03:35:29

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')

You could define more of these as you need them...

You can use template filter dictsort https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-dictsort

This should 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 %}

regroup should be able to do what you want, but is there a reason you can't order them the way you want back in the view?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!