checks.py 1.44 KB
Newer Older
1
from collections import Counter
2
3


4
def check_viewsets(viewsets):
5
    """
6
7
8
9
10
    Check that if 2 serializers are registered for the same model. Then that model
    has a get_serializer method to point to the serializer to use to deserialize it.
    There should be only one of serializer being used per model. Otherwise extra
    configuration is required.

11
12
    http://localhost:5000/#/Application/Backend/models_serializers_viewsets
    """
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    # Prevent cyclic imports
    from backend_app.models.abstract.versionedEssentialModule import (
        VersionedEssentialModule,
    )

    serializers = list()
    models = []
    for viewset in viewsets:
        serializer = viewset().get_serializer_class()
        model = serializer.Meta.model

        if issubclass(model, VersionedEssentialModule):
            if serializer not in serializers:
                serializers.append(serializer)
                models.append(model)

    models = dict(Counter(models))
    for model, n in models.items():
        if n > 1:
            try:
                # Check that the model has a get_serializer method
                model.get_serializer()
35

36
37
38
39
40
41
            except AttributeError:
                raise Exception(
                    "The model {} has multiple serializers pointing to it. "
                    "In such case, you must define the get_serializer method inside the model. "
                    "Have a look at the documentation.".format(model)
                )