Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query new Django/Postgres DateRangeField

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!

like image 497
nik_m Avatar asked Oct 18 '25 16:10

nik_m


1 Answers

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.

like image 174
Anonymous Avatar answered Oct 20 '25 06:10

Anonymous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!