【发布时间】:2017-04-12 10:28:57
【问题描述】:
我正在使用 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
请参考此图片以供参考:
这里的模型 Test 11 是通过动态模型方法创建的,我无法访问该模型,添加/更改按钮也不存在,当我杀死服务器并重新启动它,动态创建的模型将被隐藏。
如何访问此模型?我是否错过了这里的任何步骤或其中有什么问题?
【问题讨论】:
-
据我所知,当 django 应用程序启动时,它会缓存所有 ModelAdmin 操作。创建新模型时,您需要跟踪 django 应用程序初始化逻辑并缓存或重新启动 Django 应用程序。
标签: django django-models django-admin