我正在尝试创建一个模型,其中一个字段应该是 Age 字段,但它不是一个简单的数字 ( IntegerField),而是需要是几个可用年龄范围的 Choice (5-8, 8-12, 12-18, 18-99, 5-99)。我正在查看 Choices 的文档,但我什至不确定我可以直接IntegerRangeField在其中使用 an ,所以我最终得到了这样的结果:
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)
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?这对我来说看起来有点尴尬,我正在考虑只使用 Char 来代替,尽管我想坚持在最后在这个字段上有一个范围......
谢谢!
Range Fields来自django的文档:
所有范围字段都转换为
psycopg2 Range objectspython 格式,但如果不需要边界信息,也接受元组作为输入。默认值包括下限,排除上限。
看来你可以用来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
Run Code Online (Sandbox Code Playgroud)
或者,您可以创建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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
364 次 |
| 最近记录: |