Anthony Graffigna
Anthony Graffigna

Reputation: 57

Django Dictsort by __str__

I have a project where one of the models is "Chassis". I want to sort these chassis in django templates by the value returned by __str__. If I write |dictsort:"__str__" it crashes. I'm currently getting around this by writing a function getIP that returns the same thing as __str__ and passing |dictsort:"getIP".

Is there a way to do this without simply rewriting the exact same code in a different function?

Upvotes: 0

Views: 251

Answers (1)

Withnail
Withnail

Reputation: 3178

Why are sorting by that in the template? Order in the view before you pass it out - generally try and keep business logic out of the templates where possible, and this sounds a lot like business logic.

As an example, one of my models:

class Event(models.Model):

    date = models.DateField()
    location_title = models.TextField()
    location_code = models.TextField(blank=True, null=True)
    picture_url = models.URLField(blank=True, null=True, max_length=250)
    event_url = models.SlugField(unique=True, max_length=250)

    def __str__(self):
        return self.event_url + " " + str(self.date)

    def save(self, *args, **kwargs):
        self.event_url = slugify(self.location_title+str(self.date))
        super(Event, self).save(*args, **kwargs)

Given the output of __str__ here is always going to be the event_url + some other stuff (as yours will be, presumably), I could use something along the lines of:

stuff_in_order = Event.objects.filter(#yourqueryhere).order_by('event_url').order_by('date')

This will have the same effect as munging the str method in your template to order your Chassis'. (sp?)

If you really need to reorder in the template, then you could use regroup.

{% regroup chassis by dealer as dealer_list %}

Upvotes: 1

Related Questions