1

主要なモデルのいくつかと、日付の降順でソートされた (集約された) エントリをページ分割するための管理ビューに対して、小さな履歴監査証跡 ( django-simple-history ) を設定しました。問題は、私が使用している方法が最適ではないことです...

historical_foo = Foo.history.all()
historical_bar = Bar.history.all()
historical_qux = Qux.history.all()

#sort the aggregate by modified date
result_list = sorted(chain(historical_foo, historical_bar, historical_qux), key=attrgetter('history_date'), reverse=True)

paginator = Paginator(result_list, 100)

try:
    result = paginator.page(page_num)
    #...

これらのテーブルが大きくなるため、これは確かにうまくスケーリングしません。集計とソートのロジックを Django / DB にプッシュする方法、または同じ結果を得るための代替アプローチはありますか?

4

2 に答える 2

2

次を使用して、すべてを1つのテーブルに保持できますcontenttypes

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class HistoryRecord(models.Model):
    history_date = models.DateTimeField()
    history_id = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    content = generic.GenericForeignKey('content_type', 'history_id')

次に、それらを作成する必要があります。

poll = Poll.history.all()[0]
record = HistoryRecord(content=poll, history_date=poll.history_date)
record.save()

または、サブクラス化できますHistoricalRecords

class IndexedHistoricalRecords(HistoricalRecords):
    def create_historical_record(self, instance, type):
        history_user = getattr(instance, '_history_user', None)
        manager = getattr(instance, self.manager_name)
        attrs = {}
        for field in instance._meta.fields:
            attrs[field.attname] = getattr(instance, field.attname)
        content = manager.create(history_type=type, history_user=history_user, **attrs)
        record = HistoryRecord(content=poll, history_date=poll.history_date)
        record.save()

次に、1 つのテーブルにクエリを実行できます。

result_list = HistoryRecord.objects.all()
paginator = Paginator(result_list, 100)
...
于 2013-04-23T16:59:28.713 に答える
1

one-to-oneすべてのモデルは、(キーを介して) 1 つのテーブルから継承できます。

そうすれば、ベーステーブルを使用してこのフィールドでdjango ORMでソートし、後で適切なインスタンスを取得できます。

最終的なインスタンスを取得する方法については、そのディスカッションを参照してください。

于 2012-10-30T08:55:05.010 に答える