在管理中显示之前对数据库中的值进行预处理
我的问题很简单,但我无法解决我的问题:每次在管理中显示该字段时,我都需要处理一个字段,因为它必须以不同的方式保存在数据库中。
例如,我需要用户在管理中输入百分比(例如 50、70 或 100),但这些值将以 0.5、0.7 或 1 的形式保存在数据库中。之后,当用户想要编辑或只是查看时对于这些值,即使它们在数据库中保存为浮点数,也不必对其进行预处理以再次将其显示为百分比(整数)。
我想:
def valid_percentage(value):
if not 0 <= value <= 1:
raise ValidationError(u'Must be a value between 0 and 100')
class PercentageField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['validators'] = kwargs.get('validators', []) + [valid_percentage]
super(PercentageField, self).__init__(*args, **kwargs)
def to_python(self, value):
return None if value is None else int(100 * value)
def get_prep_value(self, value):
return None if value is None else value/100.0
会做的。但这在保存和显示数据时都是错误的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我花了很长时间,得到了一个适用于保存的代码版本,另一个适用于显示的版本。所以这很有趣,但并不是很有用。
实现您想要的正确方法是:
在模型类定义中使用简单的 DecimalField 或 FloatField,
创建一个 ModelForm 为您的模型
定义 clean_yourpercentagefield() 在 ModelForm 中将输入值除以 100
创建并使用自定义小部件类在渲染之前将值乘以 100
如 django 自定义字段和 modelform 文档:
事实上,您还可以采取以下步骤:
创建一个 PercentageField 类覆盖 formfield()
创建 PercentageFormField 默认使用的 PercentageWidget
如果您打算这样做,您将遇到的错误您建议的方式(这是错误的)是 to_python() 被一遍又一遍地调用几次,基本上使用以下代码:
从模型表单中保存模型将输出类似以下内容:
您必须使用SubFieldMetaclass如果你坚持要以错误的方式去做。
结论: KISS FTW!
感谢 SmileyChris 帮助回答了这个问题,这可能并不完美,但我认为不分享我发现的东西就太糟糕了。
I took it pretty far, got one version of your code that works for saving, another that works for display. So that's quite some fun but not really useful.
A correct to achieve what you want is:
Use a simple DecimalField or FloatField in your Model class definition,
Create a ModelForm for your Model
Define clean_yourpercentagefield() in your ModelForm to divide input value by 100
Make and use a custom widget class to multiply the value by 100 before rendering
As stated by django custom fields and modelform documentation:
Indeed, you can also take these steps:
Create a PercentageField class overriding formfield()
Create PercentageFormField which should be called by PercentageField.formfield()
Create PercentageWidget which PercentageFormField will use by default
The error you will run into if you intent to do it the way you suggested, which is wrong, is that to_python() is called several times over and over again, basically with this code:
Saving the model from a modelform will output something like:
You'd have to use SubFieldMetaclass if you insist in wanting to do it the wrong way.
Conclusion: KISS FTW !
Credits to SmileyChris for helping in this answer, which might not be perfect but i thought it would be too bad to not share what i've found.
尝试 get_db_prep_value 然后查看数据库以查看哪一步失败了。
Try get_db_prep_value and then look into DB to see on which step does it fail.