43Tesseracts
43Tesseracts

Reputation: 4937

How to sort a django queryset when accessed via foreignkey in template

I have two models with a foreign key relation, when I loop through the Badge objects with {% for badge in badge_type.badge_set.all %} they are sorted by ID, however I want them sorted by by their sort_order or name fields, per the Meta

class BadgeType(models.Model):
    name = models.CharField(max_length=50, unique=True)

class Badge(models.Model):
    name = models.CharField(max_length=50, unique=True)
    badge_type = models.ForeignKey(BadgeType)
    sort_order = models.PositiveIntegerField(blank=True, null=True)
    ...

    class Meta:
        order_with_respect_to = 'badge_type'
        ordering = ['sort_order', 'name']

In a view, I am sending this in my context:

@login_required
def list(request):
    badge_types = BadgeType.objects.all()
    context = {"badge_types": badge_types,}
    return render(request, "badges/list.html" , context)

In the template:

{% for badge_type in badge_types %}
      {{badge_type.name}}

      {% for badge in badge_type.badge_set.all %}
          {{badge.name}}
      {% endfor %}
{% endfor %}

However, in the template they are being ordered according to their ID.

Upvotes: 2

Views: 377

Answers (1)

Paulo Pessoa
Paulo Pessoa

Reputation: 2569

You can use this template filter: dictsort

{% for badge_type in badge_types|dictsort:"name" %}
      {{badge_type.name}}

      {% for badge in badge_type.badge_set.all|dictsort:"name" %}
          {{badge.name}}
      {% endfor %}
{% endfor %}

But, i think your problem, is the order-with-respect-to

because in the model BadgeType, you don't specified the ordering.

Upvotes: 3

Related Questions