问题描述
Django 有各种可用于模型的数字字段,例如DecimalField 和 PositiveIntegerField.虽然前者可以限制为存储的小数位数和存储的字符总数,但有没有办法将其限制为存储一定范围内的 only 数字,例如0.0-5.0 ?
Django has various numeric fields available for use in models, e.g. DecimalField and PositiveIntegerField. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing only numbers within a certain range, e.g. 0.0-5.0 ?
如果做不到这一点,有没有办法限制 PositiveIntegerField 只存储例如最多 50 个数字?
Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?
更新:现在 Bug 6845 已经关闭,这个 StackOverflow 问题可能没有实际意义.- sampablokuper
Update: now that Bug 6845 has been closed, this StackOverflow question may be moot. - sampablokuper
推荐答案
您还可以创建自定义模型字段类型 - 请参阅 http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
在这种情况下,您可以继承"内置 IntegerField 并覆盖其验证逻辑.
In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.
我越想这个,我意识到这对许多 Django 应用程序有多么有用.也许 IntegerRangeField 类型可以作为补丁提交给 Django 开发人员考虑添加到主干.
The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.
这对我有用:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
然后在你的模型类中,你会像这样使用它(字段是你放置上述代码的模块):
Then in your model class, you would use it like this (field being the module where you put the above code):
size = fields.IntegerRangeField(min_value=1, max_value=50)
OR 表示负数和正数的范围(如振荡器范围):
OR for a range of negative and positive (like an oscillator range):
size = fields.IntegerRangeField(min_value=-100, max_value=100)
如果可以像这样使用范围运算符调用它,那将是非常酷的:
What would be really cool is if it could be called with the range operator like this:
size = fields.IntegerRangeField(range(1, 50))
但是,这将需要更多代码,因为您可以指定一个跳过"参数 - range(1, 50, 2) - 不过这个想法很有趣......
But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...
这篇关于如何限制 Django 模型中数值字段的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!