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

时间:2022-08-25 10:22:25

In forms, there are two fields:

在表单中,有两个字段:

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

In sql database, there two columns: year ; month, ....

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

I want to based on what users have entered in form (start_year,start_month ; end_year,end_month) as a date range to filter in database (year, month).

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

XX.objects.filter(date_range=[]), or can I put in this data_range function?

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

Following are some related code if you need.

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

the app with form where user enter the data - views.py

用户输入数据的应用程序 - 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')

to filter the database based on user's entry - views.py

根据用户的条目过滤数据库 - 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

1 个解决方案

#1


1  

If you use DateField instead of CharField (which I think you really should be doing because you are dealing with dates) like so:

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

You can filter date objects by range by doing something along the lines of:

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

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

Or if you want to filter by a specific month, you can do:

或者,如果您想按特定月份进行过滤,则可以执行以下操作:

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

See this post: Django database query: How to filter objects by date range? and this post: How do I subtract two dates in Django/Python? for more information.

看这篇文章:Django数据库查询:如何按日期范围过滤对象?这篇文章:如何在Django / Python中减去两个日期?了解更多信息。

I'm not too sure what you exactly want to accomplish but I'm sure that if you use a DateField instead of a CharField to save the dates, it would be much easier. I also suggest you read the documentation on DateField as well for more information (it can come in handy in your situation).

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

#1


1  

If you use DateField instead of CharField (which I think you really should be doing because you are dealing with dates) like so:

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

You can filter date objects by range by doing something along the lines of:

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

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

Or if you want to filter by a specific month, you can do:

或者,如果您想按特定月份进行过滤,则可以执行以下操作:

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

See this post: Django database query: How to filter objects by date range? and this post: How do I subtract two dates in Django/Python? for more information.

看这篇文章:Django数据库查询:如何按日期范围过滤对象?这篇文章:如何在Django / Python中减去两个日期?了解更多信息。

I'm not too sure what you exactly want to accomplish but I'm sure that if you use a DateField instead of a CharField to save the dates, it would be much easier. I also suggest you read the documentation on DateField as well for more information (it can come in handy in your situation).

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