Search code examples
djangopostgresqldjango-modelsmany-to-many

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?


Solution

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

    ./manage.py 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;