Skip to content Skip to sidebar Skip to footer

How To Implement Singleton In Django

I have an object that need to be instantiated ONLY ONCE. Tried using redis for caching the instance failed with error cache.set('some_key', singles, timeout=60*60*24*30) but got se

Solution 1:

This is my Singleton Abstract Model.

classSingletonModel(models.Model):
    """Singleton Django Model"""classMeta:
        abstract = Truedefsave(self, *args, **kwargs):
        """
        Save object to the database. Removes all other entries if there
        are any.
        """
        self.__class__.objects.exclude(id=self.id).delete()
        super(SingletonModel, self).save(*args, **kwargs)

    @classmethoddefload(cls):
        """
        Load object from the database. Failing that, create a new empty
        (default) instance of the object and return it (without saving it
        to the database).
        """try:
            return cls.objects.get()
        except cls.DoesNotExist:
            return cls()

Solution 2:

I found it easier to use a unique index to accomplish this

class SingletonModel(models.Model):
    _singleton = models.BooleanField(default=True, editable=False, unique=True)

    class Meta:
        abstract = True

Post a Comment for "How To Implement Singleton In Django"