Reputation: 12096
Suppose I want to have a model like this:
from django.db import models
from django.contrib.postgres.fields import DateRangeField
class QueryRange(models.Model):
name = models.CharField('Name', max_length=50)
rsv = DateRangeField()
And in shell I create some objects like this:
obj1 = QueryRange.objects.create(name='John', rsv=('2016-06-01', '2016-06-10'))
obj2 = QueryRange.objects.create(name='Peter', rsv=('2016-07-05', '2016-07-10'))
obj3 = QueryRange.objects.create(name='Chris', rsv=('2016-07-12', '2016-07-15'))
How can I query the db by asking this question: Please check and see if the date i.e '2016-07-08' is occupied or not.
Something like this won't work:
from psycopg2.extras import DateRange
rng = DateRange('2016-07-08')
QueryRange.objects.filter(rsv__contains=rng)
I have implement the same scenario with two separate date
fields (from_date
and until_date
) and works great (of course). I am just curious how can I benefit myself with the DateRangefield
.
Cheers to all Djangonauts out there!
Upvotes: 4
Views: 1961
Reputation: 12100
You're very close with your answer. When you're looking for the presence of a single date, use a date object directly:
from datetime import date
QueryRange.objects.filter(rsv__contains=date.today())
If you're using a date range to query, you're probably looking to see if there's any overlap:
rng = DateRange('2016-07-08', '2016-07-20')
QueryRange.objects.filter(rsv__overlap=rng)
Tested both examples to make sure they work.
Upvotes: 7