Skip to content

Instantly share code, notes, and snippets.

@landonstewart
Created March 4, 2021 21:40
Show Gist options
  • Save landonstewart/4ed511e9cca6534dce7a01a334f0f214 to your computer and use it in GitHub Desktop.
Save landonstewart/4ed511e9cca6534dce7a01a334f0f214 to your computer and use it in GitHub Desktop.
Django dynamic field name timedelta filter using F()
def filter_urls(urls, hours_ago=None, filter_on='created', all_records=False):
"""Generate queryset from URL model.
All records or just the ones from the urls parameter
Restrict the records to those updated before hours_ago or not at all
Args:
urls (list): A list of URLs
Kwargs:
hours_ago (int): Timedelta in hours (default: None)
filter_on (str): A field name for the time delta filter (default: 'created')
all_records (bool): Overrides urls to get all urls (default: False)
Returns:
QuerySet object
"""
# pylint: disable=no-member
if all_records:
if hours_ago: # All URLs with timedelta
u_insts = URL.objects.annotate(filter_value=F(filter_on)).filter(
filter_value__lte=timezone.now() - timedelta(hours=hours_ago))
else:
u_insts = URL.objects.all()
elif urls:
if hours_ago: # Some URLs with timdelta
u_insts = URL.objects.annotate(filter_value=F(filter_on)).filter(
url__in=urls).filter(filter_value__lte=timezone.now() -
timedelta(hours=hours_ago))
else: # Some URLs
u_insts = URL.objects.filter(url__in=urls)
else:
raise ValueError("URL Search: Parameters ambiguous")
return u_insts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment