django -连接(年、月)_range =(start_date,end_date)错误

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

In the SQL, there are Seperpated columns "year" and "month", now based on jquery datetime picker. I can get the date entry from form in the format of yyyymm, such as 201012.

在SQL中,有分离的列“year”和“month”,现在基于jquery datetime picker。我可以用yyyyymm格式从表单中获取日期条目,比如201012。

Question is how can I based on django form date entry range to filter the database.

问题是如何基于django表单日期输入范围来过滤数据库。

The following is part of views.py, the queryset sentence is not correct. Please help correct.

下面是视图的一部分。py, queryset语句不正确。请帮助纠正。

 if form.is_valid():
     start_date=form.cleaned_data['start_date'] <---format is like 201012>
     end_date=form.cleaned_data['end_date']          

     queryset=Result.objects.filter(concatenate(year,month)_range=[start_date,end_date])  <!--filter in database)

Another question is:

另一个问题是:

since it is only YYYYMM, therefore if I defined start_date like below, it would not match the date format in html (YYYYMM). So how can I change in the models.py.

因为它仅仅是yyyyymm,所以如果我像下面这样定义start_date,它将不会匹配html (yyyyymm)中的日期格式。如何改变模型。py。

I have tried something like:

我试过以下方法:

 start_date=models.DateField(auto_now=False, auto_now_add=False,default=datetime.now().strftime("%m.%Y"))  but it is not correct.

models.py :

模型。py:

start_date=models.DateField(auto_now=False, auto_now_add=False)
end_date=models.DateField(auto_now=False, auto_now_add=False)

forms.py

forms.py

start_date=forms.DateField(widget=DateInput(),required=False) 
end_date=forms.DateField(widget=DateInput(),required=False) 

Traceback after EDIT

回溯后编辑

File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\list.py" in get
  159.         self.object_list = self.get_queryset()
File "C:\Users\user\Desktop\xxxx\views.py" in get_queryset
  90.             start_date = datetime.strptime(form.cleaned_data['start_date'], '%Y%m') # format is like 201012

Exception Type: TypeError at /result_list/
Exception Value: must be string, not datetime.date

1 个解决方案

#1


1  

There are several steps you need to take for this to work:

你需要采取以下几个步骤:

  1. Configure your form field to accept dates in the "YYYYMM" format. In your Form class:

    将表单字段配置为接受“yyyyyymm”格式的日期。在表单类:

    start_date=forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'], required=False) 
    end_date=forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'], required=False)
    

This will allow Django to automatically parse your form data and save it correctly as a datetime object. Note that it will be stored as a full date (defaulting to the first of the month) - you cannot use a DateField and ask it to store anything other than a full date.

这将允许Django自动解析表单数据并将其正确地保存为datetime对象。注意,它将被存储为一个完整的日期(默认为本月的第一个月)——您不能使用DateField并要求它存储除完整日期以外的任何内容。

  1. In your Model, set your defaults like so:

    在模型中,设置默认值如下:

    start_date=models.DateField(auto_now_add=True)
    

You have to store a full date in a DateField, so just let it default to the current date. This will still give correct results below (assuming the day of the month doesn't matter to you).

您必须在DateField中存储一个完整的日期,因此让它默认为当前日期。这仍然会给出正确的结果(假设这个月的哪一天对你来说并不重要)。

  1. Your query logic would now be as follows:

    您的查询逻辑如下:

    if form.is_valid():
        # Convert the form inputs into valid datetime objects
        start_date = form.cleaned_data['start_date']
        end_date = form.cleaned_data['end_date']     
    
        # These are full dates... but we only want to compare month and year, so:
    
        queryset=Result.objects.filter(
            start_date__year__gte=start_date.year,
            start_date__month__gte=start_date.month, 
            end_date__year__lte=end_date.year,
            end_date__month__lte=end_date.month)
    

#1


1  

There are several steps you need to take for this to work:

你需要采取以下几个步骤:

  1. Configure your form field to accept dates in the "YYYYMM" format. In your Form class:

    将表单字段配置为接受“yyyyyymm”格式的日期。在表单类:

    start_date=forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'], required=False) 
    end_date=forms.DateField(widget=DateInput(format='%Y%m'), input_formats=['%Y%m'], required=False)
    

This will allow Django to automatically parse your form data and save it correctly as a datetime object. Note that it will be stored as a full date (defaulting to the first of the month) - you cannot use a DateField and ask it to store anything other than a full date.

这将允许Django自动解析表单数据并将其正确地保存为datetime对象。注意,它将被存储为一个完整的日期(默认为本月的第一个月)——您不能使用DateField并要求它存储除完整日期以外的任何内容。

  1. In your Model, set your defaults like so:

    在模型中,设置默认值如下:

    start_date=models.DateField(auto_now_add=True)
    

You have to store a full date in a DateField, so just let it default to the current date. This will still give correct results below (assuming the day of the month doesn't matter to you).

您必须在DateField中存储一个完整的日期,因此让它默认为当前日期。这仍然会给出正确的结果(假设这个月的哪一天对你来说并不重要)。

  1. Your query logic would now be as follows:

    您的查询逻辑如下:

    if form.is_valid():
        # Convert the form inputs into valid datetime objects
        start_date = form.cleaned_data['start_date']
        end_date = form.cleaned_data['end_date']     
    
        # These are full dates... but we only want to compare month and year, so:
    
        queryset=Result.objects.filter(
            start_date__year__gte=start_date.year,
            start_date__month__gte=start_date.month, 
            end_date__year__lte=end_date.year,
            end_date__month__lte=end_date.month)