I have this function that gets the closest matches for every countryCode (based on a date in epoch time) from a model to a certain given time, dt being the the difference in time, limit being the amount of best matches (but one per country) and max offset being the max amount it can differ from the given date, it's pretty slow right now so I was wondering if there is a faster way to do this.
Code:
def get_tile_increase(dt=86400, limit = 10, maxoffset=0.1):
t = time.time() - dt
qer = CountryTilePrice.objects.filter(epochDate__gte=t - dt*maxoffset, epochDate__lte=t + dt*maxoffset)
.annotate(abs_diff=Func(F('epochDate') - t, function='ABS')).order_by('countryCode', '-abs_diff').distinct('countryCode')
ret = []
for i in qer:
ret.append([i.countryCode, CountryTilePriceLatest.objects.get(countryCode=i.countryCode).totalTilesSold - i.totalTilesSold,
i.country.countryName if len(i.country.countryName) <= 22 else i.country.countryName[:19] + '...'])
ret.sort(key=lambda x: x[1], reverse=True)
return ret[:limit]
question from:
https://stackoverflow.com/questions/65940697/fastest-way-to-getting-closest-date-matches-from-a-django-model 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…