Django: how to concatenate a split integer field (Year, month) as a date range for filtering a database

There are two fields in forms:

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

There are two columns in the sql database: year; month,....

I want based on what users entered into the form (start_year, start_month; end_year, end_month) as the date range for filtering in the database (year, month).

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

Below is some code if you need to.

application with a form in which the user enters data - 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 a database based on a user record - 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
+4
source share
1 answer

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: ? : Django/Python? .

, , , DateField CharField , . DateField, ( ).

+1

Source: https://habr.com/ru/post/1612181/


All Articles