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

前端 未结 2 1068
无人及你
无人及你 2021-01-01 17:11

On upgrade to Django 1.9, I now get the warning

RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.
2条回答
  •  时光取名叫无心
    2021-01-01 17:45

    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

提交回复
热议问题