Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Created March 8, 2019 17:41
Show Gist options
  • Save mark-mishyn/084bc926d00d9d8c7a1e5cff91ae81ac to your computer and use it in GitHub Desktop.
Save mark-mishyn/084bc926d00d9d8c7a1e5cff91ae81ac to your computer and use it in GitHub Desktop.
Filter Django queryset by birthdays in date range
def filter_by_birthdays(qs, from_date, to_date):
# Build the list of month/day tuples.
dates = []
while from_date < to_date:
dates.append((from_date.month, from_date.day))
from_date += timedelta(days=1)
# Transform each into queryset keyword args.
dates = (dict(
zip(('date_of_birth__month', 'date_of_birth__day'), t)) for t in dates)
query = reduce(operator.or_, (Q(**d) for d in dates))
return qs.filter(query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment