python - 如何覆盖 Django 中模型的 __new__ 元类方法

标签 python django

我在 Django 中使用 Django 1.6model inheritance。我想做的是, Hook 新类扩展。

它会像用 Python 那样完成,

class Meta(type):
    def __new__(cls, name, bases, newattrs):
        do_what_you_want_before()
        result= super(Meta, cls).__new__(cls, name, bases, newattrs)
        do_what_you_want_after()
        return result

class Foo:
    __metaclass__ = Meta

class SubFoo(Foo):
    pass

当这部分代码被初始化时,自定义的__new__方法将被调用。

我如何在 Django 中使用模型继承来做到这一点。当您尝试使用 Django 模型执行此操作时,会出现如下错误:

TypeError: Error when calling the metaclass bases
    metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

谢谢。

最佳答案

不是从 type 继承,而是从 django.db.models.base.ModelBase ( source ) 继承。

关于python - 如何覆盖 Django 中模型的 __new__ 元类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25527275/

相关文章:

python - 序列化器 - Django REST 框架(AttributeError : Got AttributeError when attempting to get a value for field `user` on serializer)

python - django.template.exceptions.TemplateDoesNotExist : registration/login. html

python - Django - 过滤 prefetch_related 查询集

python - Django 或 mod_wsgi 在运行时会修改 sys.path 吗?

python - 如何在 PySpark 1.6 中将 DataFrame 列从字符串转换为 float / double ?

python - 链接到 Boost python 3.6。找不到 boost_python 而不是 boost_python3

python - 如何在Python上比较Excel工作表中的日期以进行值填充

python - 如何模拟我无法访问的对象属性?

python - 如何从 Django 目录外部访问文件

Django Celery 多个工作线程和多个队列