Tuesday, September 10, 2013

Re: QuerySet to cover a date range



On Tue, Sep 3, 2013 at 7:02 PM, Neil Menne <the1evilgenius@gmail.com> wrote:
Hello, all!

I'm trying to get a query set that 'covers' a date range. Each object only contains a single date. For example, given a start date of 8/1/13 and an end date of 8/30/13, I want to filter my objects such that i get the first object prior to the start date and all objects up to the end date.

Example data: If the database contains two objects whose dates are 7/30/13 and 8/15/13, I would want both of these in my query set. Additionally, if there was an object with a date of 7/15/13, I would want my filters to exclude this one as the 7/30/13 object covers the start date.

I do something like: 

   MyModel.objects.filter(date__gte=start_date, date__lte=end_date).order_by('date').

This only gets me those dates who are perfectly within the start and end date range, so it would return the 8/15/13 object. I can follow it up with something like:

   MyModel.objects.filter(date__lt=start_date).order_by('-date')[:1]

This gets me only the 7/30/13 object and excludes the 7/15/13 object as intended. I can then join the two QuerySets and go on my merry way...

My question is this: Is there a way to do this in a single query?

Thanks for your time,
Neil

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate