versionedEssentialModule.py 1.73 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
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
Florent Chehab's avatar
Florent Chehab committed
11
from reversion.models import Version
12
13
14
15


class VersionedEssentialModule(EssentialModule):
    """
16
    Custom EssentialModule that will be versioned in the app
17
18
19
20
21
    """

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

Florent Chehab's avatar
Florent Chehab committed
22
23
24
25
26
27
28
29
30
31
    def delete(self, using=None, keep_parents=False):
        """
        Override the default delete behavior to make sure
        versions instances corresponding to the
        deleted instance are also deleted.
        """
        # We need to delete the versions first. Otherwise for some reason it wouldn't work.
        Version.objects.get_for_object(self).delete()
        super().delete(using, keep_parents)

32
33
34
35
36
37
    class Meta:
        abstract = True


class VersionedEssentialModuleSerializer(EssentialModuleSerializer):
    """
38
    Serializer for versioned models
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    """

    # 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):
    """
58
    Viewset for the versioned models
59
60
61
    """

    serializer_class = VersionedEssentialModuleSerializer