之前,我有一个这样的模型类:Django1.1模型字段值预处理返回
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
NoteContentField是一个自定义子类CharField的是覆盖to_python方法的目的做一些Twitter文本转换处理。
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
value = super(NoteContentField, self).to_python(value)
from ..utils import linkify
return mark_safe(linkify(value))
但是,这不起作用。
当我保存注意对象是这样的:
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
的交谈值保存到数据库中,这不是我想看到的。
我想要做的是将原始内容保存到数据库中,并且只在稍后访问内容属性时进行转换。
你能告诉我这有什么问题吗?
感谢皮埃尔和丹尼尔。
我已经知道了什么是错的。
我想文本转换代码应该也在to_python或get_db_prep_value,这是错误的。
我应该重写他们两个,让to_python进行转换和get_db_prep_value返回unconversed值:
from ..utils import linkify
class NoteContentField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
self._raw_value = super(NoteContentField, self).to_python(value)
return mark_safe(linkify(self._raw_value))
def get_db_prep_value(self, value):
return self._raw_value
我不知道是否有实现这个更好的办法?
谢谢。你的意思是我必须同时定义to_python和get_db_prep_value来完成这个工作吗?如果是这样,get_db_prep_value方法应该是什么? – satoru 2010-04-04 12:17:11
你是对的,丹尼尔。这是一个耻辱,我没有耐心阅读手册:( – satoru 2010-04-04 12:33:42