How delete a model instance and the instance from the OneToOne relation

I have these two models in django rest:

class CustomUser(AbstractBaseUser):
    email = models.EmailField(max_length=255, unique=True)

class Teacher(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

How can I delete the CustomUser instance related when deleting a Teacher instance?

I tried this code but it gives this error "maximum recursion depth exceeded while calling a Python object"

@receiver(pre_delete, sender=Teacher)
def delete_user(sender, instance, **kwargs):

The issue is that you're using the pre_delete signal, and as such, it deletes the CustomUser first. The CustomUser's deletion cascades and deletes your Teacher, but before deleting your Teacher the signal is called again, causing an infinite cycle.

Change pre_delete to post_delete on your @receiver.

In Your, write this code line after INSTALLED_APPS.

AUTH_USER_MODEL = 'your_app_name.CustomUser'

class Teacher(models.Model):
     user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,blank=True, null=True) or If you have separate

@receiver(pre_delete, sender=CustomUser)
def delete_user(sender, instance, **kwargs):
    user = Teacher.objects.get(user=instance)

Try This Code.

Back to Top