SubfieldBase deprecation

31 views
Skip to first unread message

matus moravcik

unread,
Dec 5, 2015, 12:04:10 PM12/5/15
to Django users
Hi, 

according to the docs, SubfieldBase is going to be removed in 1.10 and replaced by from_db_value()


What puzzles me is this:
"Note that the new approach does not call the to_python() method on assignment as was the case with SubfieldBase."

I thought that was the main point of SubfieldBase. Is there any replacement to this / what is the best way to do it if I'd like to call to_python on assignment?

Simon Charette

unread,
Dec 7, 2015, 1:06:58 PM12/7/15
to Django users
Hi Matus!


> Is there any replacement to this / what is the best way to do it if I'd like
> to call to_python on assignment?

If you'd like to have a field's `to_python()` called on assignement you should
attach a descriptor[1] on the model class on `contribute_to_class()` that calls
it.

e.g.

class Converter(object):
    def __init__(self, field):
        self.name = field.name
        self.convert = field.to_python

    def __get__(self, instance, owner=None):
        if instance is None:
            return self
        try:
            return instance.__dict__[self.name]
        except KeyError:
            return AttributeError(self.name)

    def __set__(self, instance, value):
        instance.__dict__[self.name] = self.convert(value)


class FieldConverterMixin(object):
    def contribute_to_class(model, name):
        super(FieldConverterMixin, self).contribute_to_class(model, name)
        setattr(model, name, Converter(self))

This is mostly what SubfieldBase use to do.

Cheers,
Simon
Reply all
Reply to author
Forward
0 new messages