在django自定义字段中,SubfieldBase元类做什么? [英] In a django custom field, what does the SubfieldBase metaclass do?

查看:612
本文介绍了在django自定义字段中,SubfieldBase元类做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您实现自定义Django字段时,您应该包括以下行:

  __ metaclass__ = models.SubfieldBase 

在类定义中,如:

  class SomeCustomField(models.Field):
__metaclass__ = models.SubfieldBase

这是什么?



更新:



这是源代码元类(来自Django项目):

  class SubfieldBase(type):



def __new __(cls,name,bases,attrs):
new_class = super(SubfieldBase,cls).__ new __(cls,name,bases,attrs)
new_class.contribute_to_class = make_contrib(
new_class,attrs.get('contribut_to_class')

R eturn new_class

如何引起to_python的调用?否则会被称为?

解决方案

对于Django版本< = 1.7 ,Django提供了一个元类称为 SubfieldBase



SubFieldBase to_python() 在分配。所以,当你添加了一个 __元类__ ,它会自动调用 to_python()函数将值转换为正确的Python对象。它处理从数据库加载时需要类型转换的那些字段,但不在 .values()调用或聚合中使用。



尽管Django 1.8 已经变为。已被 from_db_value()。



根据 Django 1.8文档



历史上,Django提供了一个名为 SubfieldBase 的元类,其中
始终称为 to_python()在作业。这不是很好用
自定义数据库转换,聚合或值查询,所以它
已被替换为 from_db_value()



When you implement a custom Django field, you're supposed to include this line:

__metaclass__ = models.SubfieldBase

in the class definition, as in:

class SomeCustomField(models.Field):
    __metaclass__ = models.SubfieldBase

What does that actually do?

Update:

This is the source code for the metaclass (from the Django project):

class SubfieldBase(type):
    """
    A metaclass for custom Field subclasses. This ensures the model's attribute
    has the descriptor protocol attached to it.
    """
    def __new__(cls, name, bases, attrs):
        new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
        new_class.contribute_to_class = make_contrib(
            new_class, attrs.get('contribute_to_class')
        )
        return new_class

How does that cause to_python to be called? And what would be called otherwise?

解决方案

For Django versions<=1.7, Django provides a metaclass called SubfieldBase.

The main feature of SubFieldBase is that is calls to_python() on assignment. So, when you added a __metaclass__, it will automatically call the to_python() function to convert the value into the correct Python object. It handles those fields where type conversion is needed when loading from the database but is not used in .values() calls or in aggregates.

This has been changed in Django 1.8 though. It has been replaced with from_db_value().

As per the Django 1.8 docs:

Historically, Django provided a metaclass called SubfieldBase which always called to_python() on assignment. This did not play nicely with custom database transformations, aggregation, or values queries, so it has been replaced with from_db_value().

这篇关于在django自定义字段中,SubfieldBase元类做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆