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

时间:2018-07-04 06:32:41

标签: python django django-models datefield

我想接受用户的生日,并有一个页面显示所有人的生日,而忽略了他们出生于Heres我的CustomUsers模型。

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

这是我的表格。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 datepicker加窗口小部件来选择日期。有人可以帮助我如何在我的.py中获得理想的结果吗?我觉得需要在我的order.py中添加一些内容,如果您需要我添加任何内容,请发表评论。 PS:我使用的是Django 2.0.6版本

1 个答案:

答案 0 :(得分:2)

尝试

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