gpt4 book ai didi

python - 如何获取 Django 项目的所有应用程序中某个类的所有模型

转载 作者:行者123 更新时间:2023-12-01 09:07:25 37 4
gpt4 key购买 nike

我有一个模型类AppModelActions,它继承自CustomModel,而CustomModel又继承自django.db.models,并且我在所有应用程序中使用它项目的情况。

我想从其中一个应用程序的命令文件中获取所有应用程序中 AppModelActions 的所有实例。我无法显式导入每个命令,因为我希望此命令动态工作。我尝试以编程方式导入实例,但它不起作用(我收到此错误:`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()

最佳答案

您可以通过迭代更新一组子类来获取所有子类:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

# ...

def populate_db(self):
from some_app.models import AppModelActions

children = set()
gen = [AppModelActions]
while gen:
children.update(gen)
gen = [sc for c in gen for sc in c.__subclasses__()]

# do something with children
# ...

此后,children是一个包含 AppModelActions 子类的所有模型的集合(包括该型号)。如果您不想包含 AppModelActions ,交换 while 中的两行循环。

既然你使用命令,Django会首先加载所有models.py来自已安装应用程序的文件,因此子类在 handle(..) 之前注册函数被执行,所以 children set 将包含已安装应用程序中的所有子模型。

请注意,子模型可以是抽象的,因此您可能需要执行额外的过滤,以便仅使用非抽象模型。例如,对其进行后处理:

non_abstract_children = [c for c in children if not c._meta.abstract]

关于python - 如何获取 Django 项目的所有应用程序中某个类的所有模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51939648/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com