versionedEssentialModule.py 1.86 KB
Newer Older
1
import reversion
2
from django.db import models
3 4
from rest_framework import serializers
from reversion.models import Version
5 6 7 8 9 10 11 12 13 14 15

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


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

    # 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

55 56 57 58
    class Meta:
        model = VersionedEssentialModule
        fields = EssentialModuleSerializer.Meta.fields + ("nb_version",)

59 60 61

class VersionedEssentialModuleViewSet(EssentialModuleViewSet):
    """
62
    Viewset for the versioned models
63 64 65
    """

    serializer_class = VersionedEssentialModuleSerializer