我上了模型课
AppModelActions
继承自
CustomModel
继承自
django.db.models
我在项目的所有应用程序中都使用它。
我要获取的所有实例
应用模型动作
在所有应用程序中,来自其中一个应用程序的命令文件。我不能显式地导入每个命令,因为我希望此命令动态工作。我试图以编程方式导入实例,但它不起作用(我得到这个错误:`keyError:'appModelActions')。
这是我的代码:
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from GeneralApp import models
class Command(BaseCommand):
help = _("""Run this commando to populate an empty database with initial data required for Attractora to work.
For the momment, this models are considered on 'populate_db' command:
- InventoriManagerApp.InventoryManagerAppActions """)
def populate_db(self):
applications = settings.INSTALLED_APPS
for application in applications:
try:
import applications.models
except:
pass
#from InventoryManagerApp.models import InventoryManagerAppActions
models_to_populate = (vars()['AppModelActions'])
#models_to_populate = (InventoryManagerAppActions,)
for model_to_populate in models_to_populate:
self.populate_model('InventoryManagerApp', model_to_populate)
def populate_model(self, app_label, model_to_populate):
model_to_populate_instance = model_to_populate()
content_type = ContentType.objects.get(app_label=app_label, model=model_to_populate_instance.name)
if hasattr(model_to_populate_instance, 'populate_data'):
populate_data = model_to_populate.populate_data
for record in populate_data:
for key, value in record.items():
setattr(model_to_populate_instance, key, value)
try:
model_to_populate_instance.save()
except IntegrityError:
print("{} already exists.".format(model_to_populate_instance))
# else:
# new_permission = Permission.objects.create(code_name=)
def handle(self, *args, **kwargs):
self.populate_db()