How to deal with “SubfieldBase has been deprecated. Use Field.from_db_value instead.”

╄→гoц情女王★ 提交于 2020-01-01 04:11:07

问题


On upgrade to Django 1.9, I now get the warning

RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.

I see where the problem arises. I have some custom field definitions, and in them I have __metaclass__ = models.SubfieldBase. For example,

class DurationField(models.FloatField):

    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):

    ...

If the __metaclass__ statement is deprecated, what am I supposed to replace it with exactly?

Do I just take it out and add a from_db_value method like in the example here: https://docs.djangoproject.com/en/1.9/howto/custom-model-fields/#converting-values-to-python-objects ?

And how are from_db_value and to_python different? The both seem to convert database data to Python objects?


回答1:


Yes, you should just remove __metaclass__ line and add from_db_value() and to_python():

class DurationField(models.FloatField):

    def __init__(self, *args, **kwargs):
        ...

    def from_db_value(self, value, expression, connection, context):
        ...

    def to_python(self, value):
        ...

As described here: https://docs.djangoproject.com/en/1.9/ref/models/fields/#field-api-reference, to_python(value) converts the value (can be None, string or object) into the correct Python object.

from_db_value(value, expression, connection, context) converts a value as returned by the database to a Python object.

So, both methods return Python objects, but they are used by Django in different situations. to_python() is called by deserialization and during the clean() method used from forms. from_db_value() is called when the data is loaded from the database




回答2:


While ozren is right, there is one huge difference, SubfieldBase had a really dirty side effect, it always called the to_python method on value assignment to the given model field. I have been recently bitten by this while upgrading from Django 1.9 to 1.10.

SEE:

https://docs.djangoproject.com/en/2.1/releases/1.8/#subfieldbase



来源:https://stackoverflow.com/questions/35166085/how-to-deal-with-subfieldbase-has-been-deprecated-use-field-from-db-value-inst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!