如何处理“SubfieldBase已被弃用”。请改用Field.from_db_value。“ [英] How to deal with "SubfieldBase has been deprecated. Use Field.from_db_value instead."
问题描述
在升级到Django 1.9时,我现在收到警告。
On upgrade to Django 1.9, I now get the warning
RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.
我看到问题出现在哪里。我有一些自定义字段定义,在其中我有 __ metaclass__ = models.SubfieldBase
。例如,
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?
我只是拿出来,添加一个 from_db_value
方法,如下例所示: https://docs.djangoproject.com/en /1.9/howto/custom-model-fields/#converting-values-to-python-objects
?
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
?
而且$ code> from_db_value 和 to_python
不同?两者似乎将数据库数据转换成Python对象?
And how are from_db_value
and to_python
different? The both seem to convert database data to Python objects?
推荐答案
是的,你应该删除 __ metaclass __
行,并添加 from_db_value()
和 to_python()
:
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)
将数据库返回的值转换为Python对象
from_db_value(value, expression, connection, context)
converts a value as returned by the database to a Python object.
所以,这两种方法都返回Python对象,但Django在不同的情况下使用它们。通过反序列化和在表单中使用的 clean()
方法调用 to_python()
。 $ code> from_db_value()在从数据库加载数据时调用
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
这篇关于如何处理“SubfieldBase已被弃用”。请改用Field.from_db_value。“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!