【问题标题】:Django: How to migrate dynamic models made at runtimeDjango:如何迁移在运行时创建的动态模型
【发布时间】:2017-06-16 16:04:02
【问题描述】:

在我的 Django 应用程序中,特定的用户输入将导致创建新模型。这是我用来创建模型并注册它的代码。

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()

这成功创建了新模型,但是,当我单击模型以查看管理页面上的表格时,我收到以下错误:

关系“ExistingModel_NewModel”不存在

这通常意味着新模型更改尚未迁移。如何迁移 Django 中动态创建的模型以查看其对应的数据表?

【问题讨论】:

    标签: python django


    【解决方案1】:

    一个简单的解决方案对我有用。在创建动态模型之后,我最终运行了 makemigrationsmigrate 管理命令:

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

    【讨论】:

      【解决方案2】:

      Subprocess 可以使用 migrate 命令迁移您的模型。所以试试这个它会工作的

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

      阅读https://code.djangoproject.com/wiki/DynamicModels如果它可以帮助创建动态模型

      【讨论】:

      • 首先感谢您的好回答!它表明你完全理解我的问题!所以我在重新加载网址之前(在注册之后)和重新加载之后添加了一次。在这两种情况下,它仍然给出相同的错误。我做错了吗?
      • 你检查过 stdout 和 stderr 变量的输出吗?
      猜你喜欢
      • 2017-11-18
      • 2019-08-18
      • 2018-02-20
      • 2017-01-08
      • 2021-09-25
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多