我正在尝试创建一个模型,其中一个字段应该是Age字段,但我需要选择几个可用的年龄范围(5-8, 8-12, 12-18, 18-99, 5-99)
,而不是简单的数字((5-8, 8-12, 12-18, 18-99, 5-99)
)。我正在查看Choice的文档,但我甚至不确定我是否可以在其中直接使用IntegerRangeField
,因此我最终得到了这样的结果:
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)
这是正确的做法吗?这对我来说有点尴尬,我正在考虑用Char代替,虽然我想坚持在这个领域的最后有一个范围.
谢谢!
发布于 2016-03-04 13:10:36
来自Range Fields
在django中的文档:
所有范围字段都在python中转换为
psycopg2 Range objects
,但如果不需要边界信息,也可以接受元组作为输入。默认值包括下限,上限不包括在内。
您似乎可以使用tuples
来创建选择。
FIRST_RANGE = (5, 8) # here 5 is included and 8 is excluded
# and similarly create the other ranges and then use in AGE_CHOICES
或者,您可以创建Range
对象。
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
https://stackoverflow.com/questions/35796808
复制相似问题