如何动态添加自定义字段到模型 [英] How dynamic add custom field to model

查看:158
本文介绍了如何动态添加自定义字段到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态添加自定义字段?
我正在尝试,但是当我同步db时,该字段将不会插入到数据库中:

How add custom field dynamicly? I'm trying that, but the field won't insert into database when I sync db:

#It use as register(MyModel)
def register(model, attr="my_attr"):

    if model in registry:
        raise AlreadyRegistered(
            _('The model %s has already been registered.') % model.__name__)

    registry.append(model)
    setattr(model, attr, MyField())

    MyField().contribute_to_class(model, attr) 

#MyField.contribute_to_class
def contribute_to_class(self, cls, name):
     super(MyField, self).contribute_to_class(cls, name)

     setattr(cls, self.name, self)
     cls.add_to_class('%s_manager' %  name, MyDescriptor())

     signals.post_save.connect(self._save, cls, True)


推荐答案

p>你可能不会在没有入侵Django内部的情况下这样做。 syncdb 命令检查每个模型的元对象以获取要创建的字段列表,该列表是通过类code> django.db.models.Model 基类:

You probably cannot do that without hacking into Django's internals. The syncdb command inspects the meta object for each model to get a list of fields to create, which is created on class construction time via the metaclass of the django.db.models.Model base class:

class MyModel(models.Model):
    my_filed = models.CharField(...)

# Here, class construction is complete and your class has a _meta member.
# If you want, you can check it out in the interactive shell.
meta = MyModel._meta

课程结构完成后,例如在DEDENT跟随语句之后,元对象是固定的(不受修改模型类的影响),您将不得不破解元(这当然是可能的)以添加动态字段。但是,由于您在这里处理内部对象,可能会使您的应用程序与未来的Django版本不兼容。

After the class construction is complete, e.g. after the DEDENT following the class statement, the meta object is fixed (not affected by modifying the model class) and you will have to hack the meta (which is of course possible) in order to add dynamic fields. But since you are messing with internal objects here, it could render your app incompatible with future releases of Django.

剩下的问题是:为什么要这样做?由于数据库表通常仅在部署应用程序时创建一次,因此模型是静态。

The remaining question is: Why would you want to do that? Since database tables are usually only created once when deploying your app, models are kind of "static".

这篇关于如何动态添加自定义字段到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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