I'm using Django 2.2
In my application, there is a shared user feature and every shared user are added to User model with is_shared
field set to True.
The shared user is linked to a user in SharedUser model like
class SharedUser(models.Model)
user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='owner_user')
shared_user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='shared_user')
On delete of a record from SharedUser model, I also have to delete the linked shared_user
record from the User model. For that I'm using the post_signal
receiver.
receivers.py
@receiver(post_delete, sender=SharedUser, dispatch_uid='post_delete_shared_user')
def post_delete_shared_user(sender, instance, *args, **kwargs):
try:
if instance and instance.shared_user:
owner = instance.user
instance.shared_user.delete()
except:
pass
and the receiver is loaded in the app.py config
class SharedUsersConfig(AppConfig):
name = 'shared_users'
def ready(self):
from . import receivers
Now, whenever a record from the SharedUser model is deleted, it makes a lot of SQL queries.
When the import receivers
is removed from the apps.py file.
There are a lot more SQL queries being made when the receiver is used to delete the associated user.
In my use case, there is nowhere the shared_user
is associated to any other model other than SharedUser model.
- How can I reduce the query on deleting a user?
- Can I disable sending the signal when the user is deleted for this scenario only? Since a
shared_user
is not related to any other model.