Django Delete a many to many field


I have 2 models User which is Django’s auth_user, and HostCourse which has a many to many relationship with User

class HostCourse(TimeStamped, models.Model):
    created_by = models.ManyToManyField(User, blank=True)

I am using Postgresql, and I am trying to delete the data in HostCourse from dbshell.

delete from courses_hostcourse;

When I delete some data from HostCourse, it throws the following error:

ERROR: update or delete on table "courses_hostcourse" violates foreign key constraint "courses_hostcourse_c_hostcourse_id_ec1070c3_fk_courses_h" on table "courses_hostcourse_created_by"

If I’ll include on_delete=models.CASCASE, will it also delete the users of the respective HostCourse? If yes, how can I find a workaround, so that it deletes courses and not users?


Well usually you would do it in the python shell like this:

./ shell
>>> HostCourse.objects.all().delete()

ManyToManyField creates a new table, so you want to delete all objects there first. The users won’t be deleted
In the db_shell you would do:

delete from courses_hostcourse_created_by;
delete from courses_hostcourse;

Answered By – ChrisRob

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published