Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Created March 8, 2019 17:35
Show Gist options
  • Select an option

  • Save mark-mishyn/02bcc4cb4f00d852afbf6fa3744d7316 to your computer and use it in GitHub Desktop.

Select an option

Save mark-mishyn/02bcc4cb4f00d852afbf6fa3744d7316 to your computer and use it in GitHub Desktop.
Order Django queryset by upcoming birthdays
def order_by_upcoming_birthdays(qs, from_date=None, birthday_field_name='date_of_birth'):
from_date = from_date or now().date()
qs = users_qs.annotate(
month=Extract(birthday_field_name, 'month'),
day=Extract(birthday_field_name, 'day'))
whens = []
for i in range(12):
whens.append(When(month=(from_date + relativedelta(months=i)).month, then=i))
return qs.annotate(month_order=Case(
*whens,
output_field=IntegerField(),
default=4)).order_by('month_order', 'day')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment