Django1.4:如何在模板中使用order_by?
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)
以上是我的models.py。
我想使用'order_by'(https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by)
和...
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'
我的views.py使用DetailView(https://docs.djangoproject.com/en/1.4/ref/class-based-views/#detailview)。
和
customerDetail.html
<table class="table table-bordered" style="width: 100%;">
<tr>
<td>Note</td>
</tr>
{% for i in customerDetail.notes.all.order_by %}<!-- It's not working -->
<tr>
<th>({{ i.date }}) {{ i.contents }}[{{ i.writer }}]</th>
</tr>
{% endfor %}
</table>
我想在模板中使用order_by ...
我该怎么办?
答案 0 :(得分:8)
查看dictsort过滤器,它几乎就是我想要的内容。
答案 1 :(得分:5)
order_by至少需要一个参数,Django不允许您将参数传递给模板中的函数或方法。
一些替代方案是:
queryset|order_by:'somefield'
(see this snippet)