Ordering a Django QuerySet by a datetime's month/day?

前端 未结 5 603
太阳男子
太阳男子 2021-01-02 16:00

I have a list of people, each person having a birthdate, which is predictably stored in a DateField. I\'m trying to create a list of those people—sorted by the

5条回答
  •  离开以前
    2021-01-02 16:43

    I tested using django 1.10.8

    from django.db.models.functions import Extract
    from your_project.your_app.models import Person
    
    
    CHOICE_MONTH = (
        (None, '--'),
        (1, 1),
        (2, 2),
        (3, 3),
        (4, 4),
        (5, 5),
        (6, 6),
        (7, 7),
        (8, 8),
        (9, 9),
        (10, 10),
        (11, 11),
        (12, 12),
    )
    
    class PersonSearchForm(forms.Form):
    
        name = forms.CharField(label=u'name', required=False)
        month = forms.ChoiceField(label='month', choices=CHOICE_MONTH, required=False)
    
        def __init__(self, *args, **kwargs):
            self.corporation = kwargs.pop('corporation', None)
            super(PersonSearchForm, self).__init__(*args, **kwargs)
    
        def get_result_queryset(self):
            q = Q(corporation=self.corporation)
            if self.is_valid():
                name = self.cleaned_data['name']
                if name:
                    q = q & Q(name__icontains=name)
                month = self.cleaned_data['month']
                if month:
                    q = q & Q(month=int(month))
    
            return Person.objects.annotate(month=Extract('birthday', 'month'),
                                           day=Extract('birthday', 'day')).filter(q).order_by('month', 'day')
    

提交回复
热议问题