Django:如何连接分隔的整数字段(年、月)作为日期范围来过滤数据库

2024-04-23 20:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在表单中,有两个字段:

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数据库中,有两列:年;月。。。。在

我想根据用户在表单中输入的内容(开始年份,开始月份;结束年份,结束月份)作为在数据库中过滤的日期范围(年,月)。在

在二十、 对象.过滤器(date_range=[]),或者我可以加入这个data_range函数吗?在

下面是一些相关的代码,如果你需要的话。在

用户输入数据的表单应用程序-视图.py

^{pr2}$

根据用户输入过滤数据库-视图.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

Tags: selfnonegetobjectsmodelscontextyearstart
1条回答
网友
1楼 · 发布于 2024-04-23 20:31:16

如果您使用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() 

通过执行以下操作,可以按范围筛选日期对象:

^{pr2}$

或者,如果要按特定月份筛选,可以执行以下操作:

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上的文档以获取更多信息(它在您的情况下会很有用)。在

相关问题 更多 >