[Fixed]-Django Dictsort by __str__

1👍

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

Leave a comment