开发者

Mixin Field into Existing and uneditable django model

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.mod开发者_Go百科els.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!


Mixins work great with adding attributes and methods, but not fields.

In app1.models.py, do this instead:

from django.db import models
from app2.models import BlogPost

custom_field_name = models.CharField(max_length=200)
custom_field_name.contribute_to_class(BlogPost, "custom_field_name")

I think also the app1 app should come after app2 in INSTALLED_APPS for this to work.

Here is an explanation on contribute_to_class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜