Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to migrate dynamic models made at runtime

Tags:

python

django

In my Django app, a specific user input will result in the creation of a new model. Here is the code I am using 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 the new model, however, when I click on the model to see the table on the admin page, I get the following error:

relation "ExistingModel_NewModel" does not exist

This usually means that the new model changes have not been migrated. How can I migrate dynamically created models in Django to see their corresponding data tables?

like image 440
cookiedough Avatar asked Jun 16 '17 16:06

cookiedough


2 Answers

A simple solution worked for me. I ended up running the makemigrations and migrate management commands like so, after creating the dynamic model:

from django.core.management import call_command
call_command('makemigrations')
call_command('migrate')
like image 82
cookiedough Avatar answered Sep 28 '22 03:09

cookiedough


Subprocess can migrate your model using 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)

Read also this https://code.djangoproject.com/wiki/DynamicModels If it can help for create dynamic model

like image 43
Neeraj Kumar Avatar answered Sep 28 '22 02:09

Neeraj Kumar