如何获取多个对象的第一次和最后一次更新的修订日期?

问题描述 投票:0回答:1

我需要对SomeModel的所有实例进行批量查询,并使用创建日期和上次更新来注释它们。这是我尝试过的,非常慢:

query = SomeModel.objects.all()
for entry in query:
    last_updated_date = entry.details.history.last().history_date
    created_date = entry.details.history.first().history_date
    csv_writer.writerow([entry.name, last_updated_date, created_date])

我怎样才能优化代码?我想问题是我正在进行大量的SELECT查询,可能会有一些更复杂的问题。

django django-models django-queryset django-orm django-simple-history
1个回答
0
投票

你可以尝试这样(使用subquery):

from django.db.models import OuterRef, Subquery
from simple_history.models import HistoricalRecords

histories = HistoricalRecords.objects.filter(pk=OuterRef('details__history')).order_by('history_date')

SomeModel.objects.annotate(created_date=Subquery(histories.values('history_date')[:1])).annotate(last_updated==Subquery(histories.order_by('-history_date').values('history_date')[:1]))

仅供参考:这是一个未经测试的代码。

© www.soinside.com 2019 - 2024. All rights reserved.