下面的代码出现了运行时问题:
# filter start and end date
matches = database.objects.filter(start__gte= Start, end__lte= End)
# iterate through matches
for Item in matches:
# filter database again
test = database.objects.filter(cm1=Item.cm1, cm2=Item.cm2, cm3=Item.cm3)
# compare first item of filter with iterated Item
if test[0] == Item:
TrueRun = True
else:
TrueRun = False我有一个大约80k行的数据库。在第一步中,我筛选想要查看的行,通常应该在8k左右。在第二步中,我将遍历所有这些项,并检查它们是否是唯一的,还是具有某些特定属性(cm1、cm2、cm3)的第一项。
现在的问题是,我做8k数据库查询,总共需要15分钟。有没有任何方法来加速这一点,例如,在循环之前使用一个包含cm1及其“匹配行”的所有可能性的dict?
谢谢你的帮忙!
__________________________
评论后的编辑
我的模型的默认顺序与这里的使用方式不同。在程序中,我有大约25种模型,并检查其中的12种模式是否相等。
循环的其余部分不应该很有趣,因为之前有另一种检查TrueRun的方法,大约花了2分钟。唯一改变的是内部#
equalnessList = ['cm1','cm2', 'cm3']
for idx, Item in enumerate(matches):
#-----------------#
TrueRun = True
listTrue = []
for TrueIdx,TrueItem in enumerate(listTrue):
EqualCount = 0
for equCrit in equalnessList:
if getattr(Item,equCrit)!=getattr(matches[TrueItem],equCrit):
EqualCount += 1
if EqualCount == len(equalnessList):
TrueRun = False
break
#------------------#
# Some stuff in here, that can't be changed
if TrueRun:
resDict[getattr(Item,'id')] = [True]
listTrue.append(idx)
else:
resDict[getattr(Item,'id')] = [False]这里的问题是,它不能正常工作,并且没有在筛选日期之外使用数据库条目进行检查。
发布于 2017-04-26 17:35:08
您可能需要调整这个以满足您的需求。特别是,您需要在每个cm1, cm2, cm3组中维护原始排序顺序。
matches = database.objects.filter(start__gte=Start, end__lte=End)
all_objects = database.objects.all().order_by('cm1', 'cm2', 'cm3', 'sequence')
# replace 'sequence' by field(s) that model is sorted on by default
results_dict = {}
cm1 = None
cm2 = None
cm3 = None
first = False
for obj in all_objects:
if (obj.cm1 != cm1) or (obj.cm2 != cm2) or (obj.cm3 != cm3):
cm1 = obj.cm1
cm2 = obj.cm2
cm3 = obj.cm3
first = True
if obj.start >= Start and obj.end <= End:
results_dict[obj.id] = first
first = False发布于 2017-04-26 12:12:06
# filter start and end date
matches = database.objects.filter(start__gte=Start, end__lte=End)
# iterate through matches
for item in matches:
# filter database again and get the id of the first element matched
first_item = database.objects.filter(cm1=item.cm1, cm2=item.cm2, cm3=item.cm3).values('id').first()
# compare first item id with the id of filtered "item"
if first_item['id'] == item.id:
TrueRun = True
else:
TrueRun = Falsehttps://stackoverflow.com/questions/43633400
复制相似问题