Django1.4:如何在模板中使用order_by?

10 投票
2 回答
14773 浏览
提问于 2025-04-17 15:45

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...

我该怎么做呢?

2 个回答

14

看看这个 dictsort 过滤器,我觉得它正好是你需要的东西。

8

order_by 至少需要一个参数,而 Django 不允许你在模板中给函数或方法传递参数。

有一些替代方案:

  • 可以使用 Jinja2 模板引擎,代替 Django 自带的模板引擎(Jinja2 允许你给方法传递参数,而且据说性能更好)
  • 在视图中对数据集进行排序
  • 使用 "Meta:ordering" 属性来为你的模型定义默认的排序规则
  • 编写一个自定义过滤器,这样你就可以用 queryset|order_by:'somefield' 的方式进行排序(查看这个代码片段
  • 正如 Michal 所建议的,你可以编写一个 自定义管理器,里面包含你需要的排序方法

撰写回答