Reputation: 7605
I'm trying to create a model where one of the fields should be an Age field, but that instead of being a simple number (IntegerField
), I needed to be a Choice of several available age ranges (5-8, 8-12, 12-18, 18-99, 5-99)
. I'm looking at the documentation of Choices, but I'm not even sure I can use directly an IntegerRangeField
in this, so I ended up with something like this:
class Person(models.Model):
FIRST_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(5), MaxValueValidator(8)])
SECOND_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(8), MaxValueValidator(12)])
THIRD_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(12), MaxValueValidator(18)])
FOURTH_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(18), MaxValueValidator(99)])
FIFTH_RANGE = IntegerRangeField(blank=True, validators=[MinValueValidator(18), MaxValueValidator(99)])
AGE_CHOICES = (
(FIRST_RANGE, '5-8'),
(SECOND_RANGE, '8-12'),
(THIRD_RANGE, '12-18'),
(FOURTH_RANGE, '18-99'),
(FIFTH_RANGE, '5-99'),
)
age = models.IntegerRangeField(blank=True, choices=AGE_CHOICES)
Is this the correct approach for this? This looks a bit awkward to me, I'm considering just using Char instead, although I'd like to stick to a have a Range on this field at the end...
Thanks!
Upvotes: 2
Views: 383
Reputation: 19831
From the documentation of Range Fields
in django:
All of the range fields translate to
psycopg2 Range objects
in python, but also accept tuples as input if no bounds information is necessary. The default is lower bound included, upper bound excluded.
It seems you can use tuples
to create the choices.
FIRST_RANGE = (5, 8) # here 5 is included and 8 is excluded
# and similarly create the other ranges and then use in AGE_CHOICES
Alternatively, you can create the Range
objects.
from psycopg2.extras import Range
FIRST_RANGE = Range(lower=5, upper=8, bounds='[)')
# bounds: one of the literal strings (), [), (], [], representing whether the lower or upper bounds are included
Upvotes: 5