社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何在Django项目的所有应用程序中获取类的所有模型

HuLu ViCa • 5 年前 • 1345 次点击  

我上了模型课 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()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37931
 
1345 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    6 年前

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

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 (包括这个型号)。如果你不想包括 应用模型动作 ,交换 while 循环。

由于使用命令,Django将首先加载 models.py 来自已安装应用程序的文件,因此子类在 handle(..) 函数被执行,因此 儿童 集合将包含中的所有子模型 安装 应用程序。

注意,子模型可以 摘要 ,因此您可能需要执行额外的筛选,以便 -使用抽象模型。例如,后处理时使用:

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