Django 如何按日月顺序对日期字段进行排序以显示生日列表



我想接受用户的生日,并有一个页面显示每个人的生日,忽略他们出生的年份 这是我对自定义用户的 models.py:

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
}
)
}

我正在使用引导日期选择器和小部件来选择日期。有人可以帮助我如何在.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')

最新更新