versionedEssentialModule.py 1.57 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
from django.db import models

import reversion
from backend_app.models.abstract.essentialModule import (
    EssentialModule,
    EssentialModuleSerializer,
    EssentialModuleViewSet,
)
from backend_app.signals.squash_revisions import new_revision_saved
from rest_framework import serializers


class VersionedEssentialModule(EssentialModule):
    """
    Custom EssentialModule that will be versionned in the app
    """

    # We store the current number of versions for better performance
    nb_versions = models.PositiveIntegerField(default=0)

    @classmethod
    def get_serializer(cls):
        """
            This function is required for handling
            versioning easily.
            You have to put the correct value in each subclass
        """
        raise Exception("Get_serializer must be redefined in subclass")

    class Meta:
        abstract = True


class VersionedEssentialModuleSerializer(EssentialModuleSerializer):
    """
    Serializer for versionned models
    """

    # Add a nb_versions field
    nb_versions = serializers.IntegerField(read_only=True)

    def save(self, *args, **kwargs):
        """
        Custom save function to use reversion.
        """

        with reversion.create_revision():
            res = super().save(*args, **kwargs)
            reversion.set_user(res.updated_by)
        new_revision_saved.send(sender=self.__class__, obj=self.instance)
        return res


class VersionedEssentialModuleViewSet(EssentialModuleViewSet):
    """
    Viewset for the versionned models
    """

    serializer_class = VersionedEssentialModuleSerializer