Sorting related items in a Django template

后端 未结 4 1184
孤城傲影
孤城傲影 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...

提交回复
热议问题