python – Django:如何将分隔的整数字段(年,月)连接为日期范围以过滤数据库

在表单中,有两个字段:

class Input(models.Model):
    start_year=models.CharField(max_length=100)
    start_month=models.CharField(max_length=100)
    end_year=models.CharField(max_length=100)
    end_month=models.CharField(max_length=100)
    ....

在sql数据库中,有两列:year;一个月……

我想根据用户在表单中输入的内容(start_year,start_month; end_year,end_month)作为在数据库中过滤的日期范围(年,月).

XX.objects.filter(date_range = []),还是可以放入这个data_range函数?

如果需要,以下是一些相关代码.

用户输入数据的表单应用程序 – views.py

def input(request):
    if request.method == 'POST':
        form = InputForm(request.POST)
        if form.is_valid():
            ...
            start_year=form.cleaned_data['start_year']
            start_month=form.cleaned_data['start_month']
            end_year=form.cleaned_data['end_year']
            end_month=form.cleaned_data['end_month']
            ...
            form.save()
            return redirect('FilterResult')

根据用户的条目过滤数据库 – views.py

class XXXView(ListView):
    context_object_name = 'XXX'
    template_name = 'XXX.html'

    queryset = XXX.objects.all()
    start_year=self.request.query_params.get('start_year', None)  /*get from the form what the user has entered
    start_month=self.request.query_params.get('start_month', None)
    end_year=self.request.query_params.get('end_year', None)
    end_month=self.request.query_params.get('end_month', None)

    objects.filter(date_range=[.....]) /*how to concatenate the year and month to put here?

    if start_year,start_month,end_year,end_month are not None:
                      queryset=queryset.filter(start_month=start_month,start_year=start_year,end_year=end_year,end_month=end_year)

    sales=XXX.objects.filter(queryset).aggregate(Sum('sales'))

    def get_context_data(self, **kwargs):
        context = super(XXXView, self).get_context_data(**kwargs)
        context['input'] = Input.objects.order_by('-id')[:1]
        return context

最佳答案 如果您使用DateField而不是CharField(我认为您应该这样做,因为您正在处理日期),如下所示:

class Input(models.Model):
    # This date has the month and the year. You can set the default day 
    # to the 1st of every month for consistency.
    startDate=models.DateField() 

    # This also has the end month and end year.
    endDate=models.DateField() 

您可以按照以下方式执行以下操作来按范围过滤日期对象:

Input.objects.filter(startDate__range=["2011-01-01", "2011-01-31"])

或者,如果您想按特定月份过滤,您可以:

Input.objects.filter(endDate__year='2011', endDate__month='01')

有关更多信息,请参阅此帖子:Django database query: How to filter objects by date range?和此帖子:How do I subtract two dates in Django/Python?.

我不太确定你想要完成什么,但我确信如果你使用DateField而不是CharField来保存日期,那就容易多了.我还建议您阅读有关DateField的文档以获取更多信息(它可以在您的情况下派上用场).

点赞