Reputation: 13
For my case it will be very important to get the order right. I need to sort my MonthlySpending objects by its index. I have tried the dictsort from django template but does not work.
I have also included the ordering in my models, however, the ordering is not shown in the HTML but it does show in the admin.
Are there anyways i can sort my objects by its index?
HTML
{% for month in object.monthlyspending_set.all|dictsort:"index" %}
<tr class="yeardata ">
<td>{{ month.name }}</td>
<td>$ {{ month.monthly_income }}</td>
<td>$ <a href="{% url 'finances:detail' month.slug %}">{{ month.target_savings }}</a></td>
<td>$ {{ month.actual_savings }}</td>
<td>{{ month.percentage_met }} %</td>
</tr>
{% endfor %}
Models.py
class MonthlySpending(models.Model):
name = models.CharField(max_length=100)
annualspending = models.ForeignKey(AnnualSpending, on_delete=models.CASCADE)
index = models.IntegerField()
slug = models.SlugField()
objects = models.Manager
class Meta:
ordering = ['index']
Upvotes: 1
Views: 8626
Reputation: 384
I recommend using order_by
on your queryset before passing it down. Documentation is here. You can do something like some_query_set.order_by("index")
in your views.
Upvotes: 1
Reputation: 696
object.monthlyspending_set.all().order_by('index') -> ascending order
object.monthlyspending_set.all().order_by('-index') -> descending order
https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by
Upvotes: 3