Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django date filter gte and lte

Tags:

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?

like image 778
ApPeL Avatar asked Mar 09 '11 11:03

ApPeL


People also ask

What is LTE and GTE Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects.

What does LTE mean in Django?

Field Lookups - lt (less than, or equal to) The lte lookup is used to get records that are less than, or equal to, a specified value.

How does filter work in Django?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.

What is get and filter in Django?

filter(**kwargs) Returns a new QuerySet containing objects that match the given lookup parameters. Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters. Follow this answer to receive notifications.


1 Answers

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)) 
like image 59
Mario César Avatar answered Nov 06 '22 05:11

Mario César