Thursday, March 31, 2016

Re: run python function in output of annotated query

Hi Fábio,

Since the deprecation of `SubfieldBase`[1] you must implement a
`from_db_value()`[2] method to convert the value as returned by the database
to the correct Python object.

Out of curiosity, is there a reason you are doing this the model level? It
looks like something that belongs to the form or template layer.

Cheers,
Simon


[1] https://docs.djangoproject.com/en/1.9/releases/1.8/#subfieldbase
[2] https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.Field.from_db_value

Le jeudi 31 mars 2016 10:15:38 UTC-4, Fabio Caritas Barrionuevo da Luz a écrit :
Hello django-users,

I have a unmanaged model, of legacy database, used only to read.

I need to clean the value of a field returned in a annotated query.

I try created a new model field inherits from TextField and override to_python method to clean the value (remove all html using python-bleach), and use in a query like:

FooBar.objects.annotate(title=ExpressionWrapper(F('html_title'), output_field=RemoveHTMLTextField())) .

I expected the method to_python was called, but it does not. 

Any idea how to solve this problem?

this is probably wrong, but it was the only way I thought so far....


####
import bleach
from django.db import models
from django.template.defaultfilters import striptags
from django.utils.safestring import mark_safe


class RemoveHTMLTextField(models.TextField):
    def to_python(self, value):
        original_value = super(RemoveHTMLTextField, self).to_python(value)
        striped_str = striptags(original_value)
        return mark_safe(bleach.clean(striped_str))
####




--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/444e33cb-5f81-4339-a751-95e7314e3770%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment