Python Django1.1返回前的模型字段值预处理
我有一个这样的模型课:Python Django1.1返回前的模型字段值预处理,python,django,django-models,Python,Django,Django Models,我有一个这样的模型课: class Note(models.Model): author = models.ForeignKey(User, related_name='notes') content = NoteContentField(max_length=256) note = Note(author=request.use, content=form.cleaned_data['content']) note.save() NoteConte
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
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对象时,如下所示:
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
转换后的值保存到数据库中,这不是我想要看到的
我试图做的是将原始内容保存到数据库中,并且仅在稍后访问内容属性时进行转换
你能告诉我这个有什么问题吗
感谢皮埃尔和丹尼尔。
我已经找出了问题所在
我认为文本转换代码应该是到_python或获取_db_prep_value,这是错误的
我应该重写这两个值,让python进行转换,并获取\u db\u prep\u值返回未转换的值:
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
我想知道是否有更好的方法来实现这一点?我认为您应该为python提供反向函数
看看这里的Django文档:您似乎只阅读了一半的文档。正如Pierre Jean在上面提到的,甚至将您链接到文档的正确部分,您需要定义反向函数,即
get\u db\u prep\u value
,这也不起作用。to_python用于将数据库值转换为python对象,这正是我想要的。但是,转换会发生两次,一次是存储字段值,一次是访问属性。谢谢。你的意思是我必须同时定义to_python和get_db_prep_值才能让它工作吗?如果是这样,那么get_db_prep_value方法应该是什么呢?你是对的,Daniel。很遗憾,我没有耐心阅读手册:(