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

你可以把所有东西放在一张桌子上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()

那么你可以查询一张表:

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

所有模型都可以从一个表继承(通过one-to-one键)。

这样,您可以使用基表在此字段上按 django ORM 排序,然后获取适当的实例。

有关获得最终实例的帮助,请参阅该讨论。

于 2012-10-30T08:55:05.010 回答