📅  最后修改于: 2023-12-03 15:14:43.854000             🧑  作者: Mango
在 Django 中,可以通过字典的形式来创建模型。这种方法可节省时间并促进代码重用,尤其在需要创建大量类似的模型时。
导入必要的模块
from django.db import models
from django.apps import apps
把你的字典转换成动态类的属性
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
# 这里可以定义默认选项
pass
if app_label:
# 如果有 app_label,则将应用程序名称设置为模型的模块名称
module = apps.get_app_config(app_label).module
attrs = {'__module__': module, 'Meta': Meta}
if fields:
attrs.update(fields)
model = type(name, (models.Model,), attrs)
if options:
# 把额外选项设置成属性
for key, value in options.items():
setattr(model._meta, key, value)
if admin_opts:
# 把额外的管理选项设置成属性
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts.items():
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
使用 create_model 函数来创建 Django 模型
my_fields = {
'title': models.CharField(max_length=255),
'description': models.TextField(blank=True),
'pub_date': models.DateTimeField(auto_now_add=True),
}
MyModel = create_model('MyModel', fields=my_fields)
保存并迁移数据库
python manage.py makemigrations
python manage.py migrate
from django.db import models
from django.apps import apps
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
pass
if app_label:
module = apps.get_app_config(app_label).module
attrs = {'__module__': module, 'Meta': Meta}
if fields:
attrs.update(fields)
model = type(name, (models.Model,), attrs)
if options:
for key, value in options.items():
setattr(model._meta, key, value)
if admin_opts:
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts.items():
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
# 使用示例:
my_fields = {
'title': models.CharField(max_length=255),
'description': models.TextField(blank=True),
'pub_date': models.DateTimeField(auto_now_add=True),
}
MyModel = create_model('MyModel', fields=my_fields)