import importlib from typing import List, Optional, Union from backend_app.models.abstract.versionedEssentialModule import ( VersionedEssentialModule, ) from django.conf import settings from .utils import load_viewsets_config def get_models( versioned: Optional[bool] = None, requires_testing: Union[None, bool, "smart"] = None, ) -> List[object]: """ Returns the list of models that could be ingered from the `viewsets_config.yml` config file. Some filtering can be applied to some attributes. If the parameter is `None` then no filtering is applied to this attribute. If the parameter is `True` or `False` the object is returned only if it matched. There is one exception for the parameter `requires_testing` if it is set to `smart` then the object is returned only if doesn't require testing or if testing is activated. """ out = list() for obj in load_viewsets_config(): if requires_testing is not None: if requires_testing == "smart": if obj.requires_testing and not settings.TESTING: continue else: if requires_testing and not settings.TESTING: continue if requires_testing and not obj.requires_testing: continue if not requires_testing and obj.requires_testing: continue module = importlib.import_module( "backend_app.models.{}".format(obj.import_location) ) Viewset = getattr(module, obj.viewset) if not hasattr(Viewset, "serializer_class"): # It is an API viewset, we don't care about it # API viewsets don't correspond to a model. continue Model = Viewset.serializer_class.Meta.model if versioned is not None: if versioned and not issubclass(Model, VersionedEssentialModule): continue if not versioned and issubclass(Model, VersionedEssentialModule): continue out.append(Model) return list(set(out)) # make sure we return each models at most once