versionedEssentialModule.py 2.02 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 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30


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")

Florent Chehab's avatar
Florent Chehab committed
31 32 33 34 35 36 37 38 39 40
    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)

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    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