Does using post_save and post_delete methods slow down over all Django project speed?

Viewed 241

I want to keep track of number of database entries. I do not want to use (in my case) Book.objects.all().count(). I know it works quite fast, but I do not think it is the good way. I have implemented Tracker class and I will be working with that singleton type of class if the numbers are needed.

Question: Does using post_save and post_delete slow down my Django project?

my source code

models.py

from django.db.models.signals import post_save, post_delete
from django.db import models


class Singleton(object):
    _instance = None

    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
        return class_._instance


class Book(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Tracker(Singleton):
    def __init__(self):
        self.__count = self.__get_numbers()

    def __get_numbers(self):
        print("I am getting records")
        return Book.objects.all().count()

    @property
    def count(self):
        return self.__count


def update_record_count(sender, **kwargs):
    tracker = Tracker()
    print("Database entries: {}".format(tracker.count))


post_save.connect(update_record_count, sender=Book)
post_delete.connect(update_record_count, sender=Book)

What I have written above is truely imaginative, just for learning purposes

1 Answers

Does using post_save and post_delete slow down my Django project?

As you may have expected, the answer is: "It depends." The signal handlers are run on the same thread that does the saving or deleting. Any code that is written in the handler (unless it's async in some fashion) will block. If your handler logic is fast, then you shouldn't notice anything. If it takes 1s then you'll see your save and delete operations take a second longer.

Related