models.py 2.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import importlib
from typing import List, Optional, Union

from django.conf import settings

from backend_app.models.abstract.my_model.myModelVersionned import MyModelVersionned

from .utils import load_viewsets_config


def get_models(
    versionned: 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 versionned is not None:
            if versionned and not issubclass(Model, MyModelVersionned):
                continue
            if not versionned and issubclass(Model, MyModelVersionned):
                continue

        out.append(Model)

    return list(set(out))  # make sure we return each models at most once