Django1.1 model field value preprocessing before returning
Posted
by Satoru.Logic
on Stack Overflow
See other posts from Stack Overflow
or by Satoru.Logic
Published on 2010-04-04T03:19:46Z
Indexed on
2010/04/04
12:43 UTC
Read the original article
Hit count: 419
Hi, all.
I have a model class like this:
class Note(models.Model):
author = models.ForeignKey(User, related_name='notes')
content = NoteContentField(max_length=256)
NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing.
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))
However, this doesn't work.
When I save a Note object like this:
note = Note(author=request.use,
content=form.cleaned_data['content'])
note.save()
The conversed value is saved into the database, which is not what I wanna see.
What I'm trying to do is to save the raw content into the database, and only make the conversion when the content attribute is later accessed.
Would you please tell me what's wrong with this?
Thanks to Pierre and Daniel.
I have figured out what's wrong.
I thought the text-conversion code should be in either to_python or get_db_prep_value, and that's wrong.
I should override both of them, make to_python do the conversion and get_db_prep_value return the unconversed value:
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
I wonder if there is a better way to implement this?
© Stack Overflow or respective owner