Created
March 4, 2021 21:40
-
-
Save landonstewart/4ed511e9cca6534dce7a01a334f0f214 to your computer and use it in GitHub Desktop.
Django dynamic field name timedelta filter using F()
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
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