Yantra Logistics
Yantra Logistics

Reputation: 308

Use date range in query filter

I have an HTML form which returns me two dates in a format like this: 2019-10-15. When I checked the type() of the date return it came out to be "str"

how can I use this string in my Django query?

Code:

start = request.POST['from']
end = request.POST['to']

foo = bar.objects.filter(dispatch_date = ??)

Upvotes: 0

Views: 797

Answers (3)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can use the range for filtering with date

You can convert string in to date by using the parse_date like this.

from django.utils.dateparse import parse_date
start = request.POST['from']
start_date = parse_date(start)

end = request.POST['to']
end_date = parse_date(end)


foo = bar.objects.filter(date__range=(start_date,end_date))

parse_date function will return None if given date not in %Y-%m-%d format so in this case you can convert into date like this

start = request.POST['from']
start_date = datetime.datetime.strptime(start, "%Y-%m-%d").date()

Upvotes: 2

Muhammed Bilal
Muhammed Bilal

Reputation: 399

VIEWS.PY

   def date_page(request): 
    f_date = request.GET.get("f_date")
    t_date = request.GET.get("t_date")


    date_queryset = Add.objects.filter(date__range=(f_date, t_date))
    for i in date_queryset:
        print (i.budget, i.date)

    return render (request , 'date_page.html',{'date_queryset':date_queryset})

HTML

    <form method="GET"> {% csrf_token %}

FROM  : <input type="date" name="f_date"> <br>  <br>  

            TO    :  <input type="date" name="t_date"> <br>  <br>  <hr>


    <input type="submit"> <br> <br>

    </form>

Upvotes: 1

Usman Maqbool
Usman Maqbool

Reputation: 3371

You have to convert the date in required format according to Model like:

start = request.POST['from']
end = request.POST['to']

start_date = datetime.strptime(start, "%Y-%m-%d %H:%M:%S.%f")

end_date = datetime.strptime(end, "%Y-%m-%d %H:%M:%S.%f")

foo = bar.objects.filter(date__range=[start_date, end_date])

"%Y-%m-%d %H:%M:%S.%f is the format you have to update according to your Model, how you defined the field.

Upvotes: 1

Related Questions