Django select_related returning empty query set if the PK deleted from other table

Consider I am having a table that having a foreignkey relation with the user model.

class MyModel(models.Model):
       created_user = models.ForeignKey(settings.AUTH_USER_MODEL)

I am taking queryset like this

qs = MyModel.objects.select_related('created_user').all()

This query working fine , but if the user deleted from the database, then it is showing empty queryset.

If you want the instance to be protected after deletion then you can use models.PROTECT option so:

class MyModel(models.Model):
       created_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)   

See all the options of ForeignKey.on_delete.

Back to Top