我需要对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查询,可能会有一些更复杂的问题。
你可以尝试这样(使用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]))
仅供参考:这是一个未经测试的代码。