Tom
Tom

Reputation: 9643

How to order a set of object in a view

My code currently lists all domains in a server using:

{% for domain in server.domain_set.all %}

I want to order the domains in the view by their url. Something like:

{% for domain in server.domain_set.all().order_by('url') %}

But I get an exception "could not parse the remainder". How can I order the list?

Upvotes: 1

Views: 90

Answers (2)

Reinout van Rees
Reinout van Rees

Reputation: 13624

The "could not parse the remainder" errors is because you're including Python code in your django template. Django doesn't allow that.

You could add a method on the model:

def sorted_domains(self):
    return self.domain_set.all().order_by('url')

And then call it like this:

{% for domain in server.sorted_domains %}

An alternative is to set the default sort order on your Domain model with a Meta attribute.

Upvotes: 4

alecxe
alecxe

Reputation: 473783

You can use a dictsort filter:

Takes a list of dictionaries and returns that list sorted by the key given in the argument.

{% for domain in server.domain_set.all|dictsort:'url' %}

Also see:

Upvotes: 3

Related Questions