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

2024-06-09 08:46:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

模型.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)

上面是我的模特。

我想使用'order_by'(https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by)

还有。。。

视图.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使用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。。。

我该怎么办?


Tags: djangonamefrompyimportbyobjectmodels
2条回答

order_by至少需要一个参数,Django不允许您将参数传递给模板内的函数或方法。

一些替代方案是:

  • 使用Jinja2模板引擎而不是Django的引擎(Jinja2将允许您向方法传递参数,据说性能更好)
  • 在视图中对数据集排序
  • 使用“Meta:ordering”属性定义模型的默认排序条件
  • 编写自定义筛选器,以便可以queryset|order_by:'somefield'see this snippet
  • 正如Michal所建议的,您可以使用预定义的方法为所需的顺序编写custom Manager

检查一下dictsort过滤器,我想这差不多就是你要找的。

相关问题 更多 >