Django:子类化 models.CharField 以在保存到数据库之前/从数据库加载之后转换值
我有一个存在编码问题的旧数据库。我无法在不破坏很多东西的情况下修复它
但我仍然想在我的 django 应用程序(django 1.2)中处理它
我认为子类化 CharField 将是一个很棒的想法,所以我这样做了:
class EncCharField(models.CharField):
__metaclass__ = SubfieldBase
def to_python(self, value):
v = super(EncCharField, self).to_python(value)
return v.encode('windows-1252').decode('windows-1251')
首先我认为它有效,但后来我遇到了另一个问题,
我在 ModelForm 和 form.save 中使用此模型,当它从表单实例创建模型实例时,调用再次EncCharField.to_python
,但这次value
编码正确,所以我的编码解码抛出异常,然后全部死掉
。有什么方法可以区分从数据库初始化模型与从表单(或其他有效对象)初始化模型的情况吗?
第二个问题,如何在保存到数据库之前重新编码(encode('windows-1251').decode('windows-1252')
)?
I have a legacy database with encoding issues. I cannot fixing it without breaking a lot of stuff
But I still want to deal with it in my side django app (django 1.2)
I thought that subclassing CharField would be an awesome idea, so I did:
class EncCharField(models.CharField):
__metaclass__ = SubfieldBase
def to_python(self, value):
v = super(EncCharField, self).to_python(value)
return v.encode('windows-1252').decode('windows-1251')
Firtst I though it worked, but then I ran into another issue
I use this model in ModelForm
and form.save
, when it creates a model instance from form instance, calls EncCharField.to_python
again, but this time with value
encoded properly, so my encoding-decoding throws an exception and all dies
So. Is there any way to distinguish situations when models in initialized from DB vs from Form (or other valid object)?
And the second question, how to re-encode back (encode('windows-1251').decode('windows-1252')
) prior to saving into the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论