Sorting related items in a Django template

后端 未结 4 1165
孤城傲影
孤城傲影 2020-12-02 10:01

Is it possible to sort a set of related items in a DJango template?

That is: this code (with HTML tags omitted for clarity):

{% for event in eventsCo         


        
相关标签:
4条回答
  • 2020-12-02 10:39

    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...

    0 讨论(0)
  • 2020-12-02 11:03

    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 %}
    
    0 讨论(0)
  • 2020-12-02 11:03

    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?

    0 讨论(0)
  • 2020-12-02 11:06

    One solution is to make a custom templatag:

    @register.filter
    def order_by(queryset, args):
        args = [x.strip() for x in args.split(',')]
        return queryset.order_by(*args)
    

    use like this:

    {% for image in instance.folder.files|order_by:"original_filename" %}
       ...
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题