Django1.4: How to use order_by in a template?
Django1.4: How to use order_by in a template?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Note(models.Model):
contents = models.TextField()
writer = models.ForeignKey(User, to_field='username')
date = models.DateTimeField(auto_now_add=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Customer(models.Model):
name = models.CharField(max_length=50,)
notes = generic.GenericRelation(Note, null=True)
Above is my models.py.
I want to use 'order_by' ( https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by)
AND...
views.py
from django.views.generic import DetailView
from crm.models import *
class customerDetailView(DetailView):
context_object_name = 'customerDetail'
template_name = "customerDetail.html"
allow_empty = True
model = Customer
slug_field = 'name'
My views.py uses DetailView ( https://docs.djangoproject.com/en/1.4/ref/class-based-views/#detailview ).
and
customerDetail.html
<table class="table table-bordered" style="width: 100%;">
<tr>
<td>Note</td>
</tr>
{% for i in customerDetail.notes.all.order_by %}<!-- It not working -->
<tr>
<th>({{ i.date }}) {{ i.contents }}[{{ i.writer }}]</th>
</tr>
{% endfor %}
</table>
I want to use order_by in a template ...
What should I do?
+3
source to share
2 answers
Order_by requires at least one argument, and Django doesn't allow you to pass arguments to a function or method inside a template.
Some alternatives:
- Use Jinja2 instead of Django engine (Jinja2 will let you pass arguments to methods and is said to work better)
- arrange dataset in view
- use the Meta: ordering " attribute to define the default ordering criteria for your models.
- write a custom filter so you can
queryset|order_by:'somefield'
( see this snippet ) - as suggested by Michal , you can write a custom Manager with predefined methods for the orderings you need.
+4
source to share