Mixin Field 到现有且不可编辑的 django 模型中
我想将一个字段混合到一个我不想编辑的现有模型中(它来自第三方项目,我宁愿让该项目保持不变)。我创建了一个简单的示例来说明我正在尝试但无法执行的操作:
在一个空的 Django 项目中,我创建了应用程序 app1 和 app2 (它们在设置中按该顺序排列)。它们看起来如下所示:
app1.models.py:
from django.db import models
from app2.models import BlogPost
class BlogPostExtend(models.Model):
custom_field_name = models.CharField(max_length=200)
class Meta:
abstract = True
BlogPost.__bases__ = (BlogPostExtend,)+BlogPost.__bases__ # this prevents MRO error
app2.models.py:
from django.db import models
class BlogPost(models.Model):
field_name = models.CharField(max_length=100)
不幸的是,当我syncdb时,这不会导致在数据库中创建custom_field_name,尽管在命令行中,如果我输入BlogPost.custom_field_name,它确实会将其识别为一个 CharField。我知道在这个简单的情况下,我可以让 BlogPost 继承自 BlogPostExtend,但在实际用例中,我无法编辑 BlogPost。
这是一个非常简单的例子,但它说明了我正在尝试做的事情。
谢谢!
I would like to mix a field into an existing model which I would rather not edit (it comes from a third party project and I would rather leave the project untouched). I have created a simple example which illustrates what I am trying but unable to do:
In an empty Django project I have created apps app1 and app2 (they are in that order in settings). They look like the following:
app1.models.py:
from django.db import models
from app2.models import BlogPost
class BlogPostExtend(models.Model):
custom_field_name = models.CharField(max_length=200)
class Meta:
abstract = True
BlogPost.__bases__ = (BlogPostExtend,)+BlogPost.__bases__ # this prevents MRO error
app2.models.py:
from django.db import models
class BlogPost(models.Model):
field_name = models.CharField(max_length=100)
Unfortunately this does not result in custom_field_name being created in the database when I syncdb, although at the command line if I type BlogPost.custom_field_name it does recognize it as a CharField. I know that in this simple case I could have BlogPost inherit from BlogPostExtend, but in the real use case I cannot edit BlogPost.
This is a very simplified example but it illustrates what I am trying to do.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mixin 非常适合添加属性和方法,但不适用于字段。
在
app1.models.py
中,执行以下操作:我认为
app1
应用程序也应该位于INSTALLED_APPS
中的app2
之后> 使其发挥作用。这是关于
contribute_to_class
的解释Mixins work great with adding attributes and methods, but not fields.
In
app1.models.py
, do this instead:I think also the
app1
app should come afterapp2
inINSTALLED_APPS
for this to work.Here is an explanation on
contribute_to_class