【问题标题】:Django1.4: How to use order_by in template?Django1.4:如何在模板中使用order_by?
【发布时间】:2013-01-29 03:35:03
【问题描述】:

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

我该怎么办?

【问题讨论】:

  • 你在customerDetailView中试过queryset = Customer.objects.order_by()吗?
  • 是的,我试过queryset = Customer.objects.order_by('note__date')queryset = Customer.objects.order_by('note__date')。但是失败了……

标签: python django django-models python-2.7 django-1.4


【解决方案1】:

查看dictsort 过滤器,我认为这正是您要寻找的。​​p>

【讨论】:

  • 这是最简单的答案,它确实适用于查询集。
【解决方案2】:

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

一些替代方案是:

  • 使用Jinja2 模板引擎而不是 Django 的模板引擎(Jinja2 可以让您将参数传递给方法,据说性能更好)
  • 在视图中对数据集进行排序
  • 使用“Meta:ordering”属性为您的模型定义默认排序标准
  • 编写自定义过滤器,以便您可以queryset|order_by:'somefield' (see this snippet)
  • 按照Michal 的建议,您可以编写一个custom Manager,并为您需要的订购提供预定义的方法

【讨论】:

  • ...或为该类使用自定义管理器,它将为您提供预定义的订购方式
  • 我不知道第四个技巧“写一个自定义过滤器,这样你就可以queryset|order_by:'somefield'”。你能给我……一些示例代码吗?
  • 反正我解决了。 class Meta: ordering = ['date'](在 models.py 中)
  • cathy answer 有这样的示例代码,似乎她使用的是相同的snippet(但她忘记将解决方案归因于original author)。此外,您需要将此文件放在some specific location 中,以便能够将其加载到模板中。
猜你喜欢
  • 2012-04-30
  • 2015-09-07
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 2011-09-17
  • 1970-01-01
  • 2017-05-16
相关资源
最近更新 更多