Django 如何按日-月的顺序对 Datefield 进行排序以显示生日列表

Django how to sort Datefield by order of Day-month to show birthday list

我想接受用户的生日,并有一个页面显示每个人的生日,忽略他们出生的年份在继承我的 models.py 的 CustomUser:

from datetime import datetime, date

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # First/last name is not a global-friendly pattern
    name = models.CharField(blank=True, max_length=255)
    birth_date = models.DateField(("Birth Date"), default=date.today)

    def __str__(self):
        return self.email

这是我的 views.py 逻辑:

def birthdaylist(request):
    if(request.user.is_authenticated):

        users=CustomUser.objects.order_by('birth_date')[:]
    # ignore the line below
    #   users= CustomUser.objects.extra(select={'birthmonth':'birth_date'},order_by=['birthmonth'])
        context={
            'users':users
        }
        return render(request,'dashboard/birthdaylist.html',context=context)
    else:
        return redirect('login')

这是我的 forms.py:

import datetime

from bootstrap_datepicker_plus import DatePickerInput
from django import forms

from django.contrib.auth.forms import UserCreationForm, UserChangeForm


from .models import CustomUser


class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        now = datetime.datetime.now()
        fields = ('username', 'email', 'gender', 'security_question', 'answer', 'birth_date', 'resume')
        widgets={
            'birth_date' :DatePickerInput(
                options={
                    'maxDate':str(datetime.datetime.now()),
                    #this needs width positioning
                }
            )
        }

我正在使用 bootstrap 日期选择器和小部件来选择日期。有人可以帮助我如何在我的 views .py 中获得预期的结果吗?我觉得我的 order.py 中需要添加一些内容,如果您需要我添加任何内容然后发表评论。 PS: 我使用的是 Django 2.0.6 版本

尝试

users=CustomUser.objects.extra(
      select={
      'month': 'extract (month from birth_date)', 
      'day': 'extract (day from birth_date)'},
       order_by=['month','day']
)

这个怎么样?

from django.db.models.functions import Extract

users=CustomUser.objects.annotate(
     month=Extract('birth_date','month'),
     day=Extract('birth_date','day')
  ).order_by('month','day')