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

cho*_*obo 3 python django django-models python-2.7 django-1.4

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)
Run Code Online (Sandbox Code Playgroud)

以上是我的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'
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

我想在模板中使用order_by ...

我该怎么办?

msc*_*msc 8

看看dictsort过滤器,它几乎就是你想要的东西.

  • 这是最简单的答案,它确实适用于查询集. (2认同)

Pau*_*ine 6

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

一些替代方法是:

  • 使用Jinja2模板引擎而不是Django的模板引擎(Jinja2将允许您将参数传递给方法,并且据说性能更好)
  • 在视图中排序数据集
  • 使用“ Meta:ordering ”属性为模型定义默认的排序条件
  • 编写一个自定义过滤器,以便您可以queryset|order_by:'somefield'请参见此代码段
  • 根据Michal的建议,您可以编写具有预定义方法的自定义Manager来满足所需的订购要求

  • 反正我解决了。`class Meta: ordering = ['date']`(在models.py中) (3认同)