How to dynamically add a custom field to a model

How to add a dynamic dynamic field? I try, but the field will not be inserted into the database when db synchronizes:

#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) 
+1
source share
2 answers

You probably can't do this without breaking into the internals of Django. The syncdb checks the meta object for each model to get a list of the created fields, which is created during the construction of the class through the class metaclass django.db.models.Model :

 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 

After the class is completed, for example. after DEDENT after the class operator, the meta object is fixed (it is not affected by a change in the model class), and you will have to hack the meta (which, of course, is possible) to add dynamic fields. But since you're messing around with internal objects here, this may make your application incompatible with future releases of Django.

The question remains: why do you need to do this? Because database tables are usually created only once when you deploy your application, the models are kind of β€œstatic”.

+3
source

I was looking for the same thing, and I had to be content with raw SQL. Although you can use something like SQLAlchemy.

0
source

All Articles