Django: how to port dynamic models at runtime

In my Django application, certain user input will lead to the creation of a new model. Here is the code that I use to create the model and register it.

model = type(model_name, (ExistingModel,), attrs) admin.site.register(model, admin_options) from django.core.urlresolvers import clear_url_caches from django.utils.module_loading import import_module reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() 

This successfully creates a new model, however, when I click on the model to see the table on the admin page, I get the following error:

relationship "ExistingModel_NewModel" does not exist

This usually means that new model changes have not been carried forward. How to transfer dynamically created models to Django to see their respective data tables?

+5
source share
2 answers

A simple solution worked for me. As a result, I created the makemigrations and migrate control makemigrations , creating a dynamic model:

 from django.core.management import call_command call_command('makemigrations') call_command('migrate') 
+5
source

A subprocess can carry your model with the migrate command. So try this, it will work

 import subprocess command = 'python manage.py migrate' proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(command) 

See also https://code.djangoproject.com/wiki/DynamicModels if this can help create a dynamic model

+2
source

Source: https://habr.com/ru/post/1268909/


All Articles