Created
September 14, 2021 18:47
-
-
Save jnm/eb0e8569ba86c6a80119f76be8c01688 to your computer and use it in GitHub Desktop.
it's quick to get by PK and horribly slow to retrieve by date, but PKs increase monotonically with dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# there's probably some way to teach postgres to do this itself | |
import datetime | |
# convenience scribbles | |
dd = [x - datetime.timedelta(days=1) for x in [datetime.date(2021, y, 1) for y in [4,5,6,7,8,9]]] | |
def print_quick(*args): | |
print(*args, end='', flush=True) | |
def find(date_value, date_field='date_created', model=Instance, pk=0, stride=10**6): | |
# Pretty slapshod; if you include `pk`, make sure it's less than what | |
# you're trying to find; if your `stride` overshoots the largest PK, | |
# you'll be lost in space | |
while True: | |
i = model.objects.filter(pk=pk).only('pk', date_field) | |
if not i: | |
pk += 1 | |
print_quick('!') | |
continue | |
i = i[0] | |
if getattr(i, date_field).date() > date_value: | |
pk -= stride | |
print_quick('>') | |
stride //= 2 | |
else: | |
pk += stride | |
print_quick('.') | |
if not stride: | |
print() | |
# This should be the first submission on the day after | |
# `date_created` | |
print(i.pk, getattr(i, date_field)) | |
break | |
return | |
while True: | |
# Find the previous submission just to double-check | |
# that it arrived on the previous day | |
i = model.objects.filter(pk=pk).only('pk', date_field) | |
if not i: | |
pk -= 1 | |
print_quick('!') | |
continue | |
i = i[0] | |
print() | |
print(i.pk, getattr(i, date_field)) | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment