I have about 10 models each of which use User as a Foreign Key. When the user is deleted, I want to set the values in each of these tables to the one who deletes the user. The users are being deleted through django admin area by authorized staff.
So, I guess I have to call a function and use SET of on_delete method to set the value.
This is the code as per documentation.
from django.db import models
from django.contrib.auth.models import User
user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
Since a staff member is deleting other users and effectively taking ownership of the objects that belongs to the deleted user the only effective solution is to override the delete_model method in Admin.
def delete_model(self, request, obj) : ''' deletes a single item. changes ownership ''' MyModel.objects.filter(user_id=obj.pk).update(user_id=request.user.id) obj.delete()
Notice that the get_sentinel_user is no longer required because delete_model already has access to request.user
Howveer you are not out of the woods yet. The admin has a bulk delete action. You actually have to disable the bulk delete action for the user admin and replace it with one of your own for you to be in full control.
The “delete selected objects” action uses QuerySet.delete() for efficiency reasons, which has an important caveat: your model’s delete() method will not be called.
Please note that bulk delete does not fire any signals for each object that's deleted so the only other django based solution that works here is to override the delete method on the User manager. However the user manager will not have access to the request.user instance ether.