django date filter gte and lte

本小妞迷上赌 提交于 2019-11-30 13:21:41

问题


I need to find data within a certain set of parameters I am building a small booking system, that lets user see what vehicles are available for booking for their little safari trip.

The system has bookings that have been entered previously or made previously by a client.

If a booking's pickup_date = 2011-03-01 and dropoff_date = 2011-03-15 and I run a query with pickup=2011-03-09 and dropoff=2011-03-14 in my views as below, it doesn't return any results to see if a booking within that timeframe has been made.

views.py

def dates(request, template_name='groups/_dates.html'):
    pickup=request.GET.get('pickup','None');
    dropoff=request.GET.get('dropoff','None');
    order = Order.objects.filter(pick_up__lte=pickup).filter(drop_off__gte=dropoff)

    context = {'order':order,}

    return render_to_response(template_name,context,
        context_instance=RequestContext(request))

Any suggestions on how to do this? Or should I be looking at an alternate way of running this query?


回答1:


Could it be posible that as your passing the raw string to the queryset is not on the correct format, try converting the strings to datetime objects.

Later you can try using the range lookup is more efficient on some DB engines and more simple to read and code.

from django.db.models import Q

start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
orders = Order.objects.filter(drop_off__gte=start_date, pick_up__lte=end_date)
# Or maybe better
orders = Order.objects.filter(Q(drop_off__gte=start_date), Q(pick_up__lte=end_date))



回答2:


Can you try this :

order = Order.objects.filter(pick_up**__date__**lte=pickup).filter(drop_off**__date__**gte=dropoff)

https://docs.djangoproject.com/fr/2.0/ref/models/querysets/#date



来源:https://stackoverflow.com/questions/5245307/django-date-filter-gte-and-lte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!