Skip to content

Instantly share code, notes, and snippets.

@jackton1
Last active February 20, 2024 04:33
Show Gist options
  • Save jackton1/0b106e1422580924ea1b13d726082067 to your computer and use it in GitHub Desktop.
Save jackton1/0b106e1422580924ea1b13d726082067 to your computer and use it in GitHub Desktop.
Django Postgres range field lookups

https://www.postgresql.org/docs/9.3/functions-range.html

from django.contrib.postgres.fields import RangeField
from django.db import models

# Is the lower bound infinite?
@RangeField.register_lookup
class LowerInf(models.Transform):
    lookup_name = 'lower_inf'
    function = 'lower_inf'
    output_field = models.BooleanField()

# Is the lower bound inclusive?
@RangeField.register_lookup
class LowerInc(models.Transform):
    lookup_name = 'lower_inc'
    function = 'lower_inc'
    output_field = models.BooleanField()
    
# Is the upper bound inclusive?
@RangeField.register_lookup
class UpperInc(models.Transform):
    lookup_name = 'upper_inc'
    function = 'upper_inc'
    output_field = models.BooleanField()

# Is the upper bound infinite?
@RangeField.register_lookup
class UpperInf(models.Transform):
    lookup_name = 'upper_inf'
    function = 'upper_inf'
    output_field = models.BooleanField()

Usage

from .models import TestModel

# Is the upper bound infinite?
objs = TestModel.objects(start_end_range__upper_inf=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment