RangeFields - a group of PostgreSQL specific fields
Syntax#
- from django.contrib.postgres.fields import *RangeField
- IntegerRangeField(**options)
- BigIntegerRangeField(**options)
- FloatRangeField(**options)
- DateTimeRangeField(**options)
- DateRangeField(**options)
Including numeric range fields in your model
There are three kinds of numeric RangeField
s in Python. IntegerField
, BigIntegerField
, and FloatField
. They convert to psycopg2
NumericRange
s, but accept input as native Python tuples. The lower bound is included and the upper bound is excluded.
class Book(models.Model):
name = CharField(max_length=200)
ratings_range = IntegerRange()
Setting up for RangeField
- add
'django.contrib.postgres'
to yourINSTALLED_APPS
- install
psycopg2
Creating models with numeric range fields
Itβs simpler and easier to input values as a Python tuple instead of a NumericRange
.
Book.objects.create(name='Pro Git', ratings_range=(5, 5))
Alternative method with NumericRange
:
Book.objects.create(name='Pro Git', ratings_range=NumericRange(5, 5))
Using contains
This query selects all books with any rating less than three.
bad_books = Books.objects.filter(ratings_range__contains=(1, 3))
Using contained_by
This query gets all books with ratings greater than or equal to zero and less than six.
all_books = Book.objects.filter(ratings_range_contained_by=(0, 6))
Using overlap
This query gets all overlapping appointments from six to ten.
Appointment.objects.filter(time_span__overlap=(6, 10))