models.py 2.12 KB
Newer Older
1
2
3
import importlib
from typing import List, Optional, Union

4
5
6
from backend_app.models.abstract.versionedEssentialModule import (
    VersionedEssentialModule,
)
7
8
9
10
11
12
from django.conf import settings

from .utils import load_viewsets_config


def get_models(
13
    versioned: Optional[bool] = None,
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
    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
54
55
        if versioned is not None:
            if versioned and not issubclass(Model, VersionedEssentialModule):
56
                continue
57
            if not versioned and issubclass(Model, VersionedEssentialModule):
58
59
60
61
62
                continue

        out.append(Model)

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