我正在使用Django 1.11,我尝试通过引用此链接https://code.djangoproject.com/wiki/DynamicModels来创建Django动态模型,通过执行它运行的每一步而没有任何问题,但是当我在Django管理员中看到注册的模型时面板,模型在相应的应用程序下可见,但它无法访问,我不知道我错过了什么。
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
# Using type('Meta', ...) gives a dictproxy error during model creation
pass
if app_label:
# app_label must be set using the Meta inner class
setattr(Meta, 'app_label', app_label)
# Update Meta with any options that were provided
if options is not None:
for key, value in options.iteritems():
setattr(Meta, key, value)
# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}
# Add in any fields that were provided
if fields:
attrs.update(fields)
# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)
# Create an Admin class if admin options were provided
if admin_opts is not None:
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
请参考此图片以供参考:
此处模型测试11 是通过动态模型方法创建的,我无法访问该模型,添加/更改按钮也不存在,当我杀死服务器并重新启动它,动态创建的模型被隐藏。
如何访问此型号?我错过了这里的任何步骤或者它有什么问题吗?
答案 0 :(得分:0)
我遇到了同样的问题,但是几行代码解决了这个问题。您将需要注册动态模型,然后重新加载并清除缓存。它看起来像这样:
from django.contrib import admin
from django.core.urlresolvers import clear_url_caches
from django.utils.module_loading import import_module
admin.site.register(model, admin_options)
reload(import_module(settings.ROOT_URLCONF))
clear_url_caches()