Search code examples
pythondjangodjango-viewsdjango-mysql

Deleting a django model class object without foreignkey warning


I have two tables in MySql created with django models.One is Students model, other is Attendance model.

class Attendance(BaseModel):
    stu = models.ForeignKey(Students, verbose_name=_("Student"))

I did't put "on_delete=models.PROTECT" to stu in Attendance class, because i need to able to delete a Student object without protection warning, if this Student is defined in Attendance as foreignkey from Students class.

Now when i delete a Students objects, the foreignkey connected records in Attendance are also deleted.

The thing i want to do is, i want to delete Students objects without warning. But i want connected foreignkey records in Attendance should stay there for historical reports.

The Students objects will be deleted without warning, and foreignkey related rows in Attendance will not be deleted.


Solution

  • By your description It's seems you should use on_delete=models.SET_NULL. By this method foreign key values are not deleted, instead their relation id to deleted item will be set to null.

    So Student object will be deleted and stu value will be set to Null.