Reputation: 3840
Let's say I have 2 models. Model_A and Model_B.
Whenever the admin user makes a change to an object of model_A, they click the "save" button.
So, when a "save" happens, I would like to send a post_save signal that creates a model that inherits from Model_B.
When I do so like the following, the models do get created but they disappear after refreshing the page, and sometimes they appear again after refreshing again. But they don't always stay on the list. (Weird, I know!)
So the code for the post_save signal is like so:
post_save.connect(create_new_model, sender=Model_A)
My create_new_model is like so:
def create_new_model(sender, instance, **kwargs):
attrs = {
'field1': models.CharField(max_length=40),
'field2': models.CharField(max_length=40),
'__module__': 'appname.models'
}
from appname.models import create_model, admin_options, modelsList
mod = create_model(name=str(len(modelsList)),
fields=attrs,
admin_opts=admin_options
)
modelsList.append(mod)
And finally, the function that creates the dynamic models (create_model) is like so:
def create_model(name, fields=None, admin_opts=None):
from appname.models import Model_A
attrs = fields
model = type(name, (Model_A,), attrs)
if admin_opts is not None:
admin.site.register(model, admin_opts)
return model
Does anyone know why this sneaky thing might be happening?
Upvotes: 0
Views: 104
Reputation: 599638
This is presumably happening because your server is using more than one process. Any dynamic class will only exist within the process that creates it; and even then it won't persist across process restarts.
I don't know what your use case is here but this is certainly not the way to do it.
Upvotes: 3