7

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 )

と...

ビュー.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 を使いたい...

私は何をすべきか?

4

2 に答える 2

9

dictsortフィルターをチェックしてください。探しているものとほぼ同じだと思います。

于 2013-02-13T15:43:10.467 に答える
7

order_by には少なくとも 1 つの引数が必要です。Django では、テンプレート内の関数またはメソッドに引数を渡すことはできません。

いくつかの代替手段は次のとおりです。

  • Django のテンプレート エンジンではなく、 Jinja2テンプレート エンジンを使用します (Jinja2 ではメソッドに引数を渡すことができ、パフォーマンスが向上すると言われています)。
  • ビューでデータセットを並べ替える
  • Meta:ordering」属性を使用して、モデルのデフォルトの順序付け基準を定義します
  • できるようにカスタムフィルターを作成しますqueryset|order_by:'somefield'このスニペットを参照
  • Michalが提案したように、必要な順序付けのために定義済みのメソッドを使用してカスタム Managerを作成できます。
于 2013-02-13T14:52:02.383 に答える