Created
March 8, 2019 17:35
-
-
Save mark-mishyn/02bcc4cb4f00d852afbf6fa3744d7316 to your computer and use it in GitHub Desktop.
Order Django queryset by upcoming birthdays
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 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