Django 删除多对多字段
Django Delete a many to many field
我有 2 个模型 User,这是 Django 的 auth_user,和 HostCourse,它与 User 有多对多的关系
class HostCourse(TimeStamped, models.Model):
created_by = models.ManyToManyField(User, blank=True)
...
我正在使用 Postgresql,我正在尝试从 dbshell 中删除 HostCourse 中的数据。
delete from courses_hostcourse;
当我从 HostCourse 中删除一些数据时,它会抛出以下错误:
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"
如果我包含 on_delete=models.CASCASE
,是否还会删除相应 HostCourse 的用户?如果是,我如何找到解决方法,以便删除课程而不是用户?
通常你会在 python shell 中这样做:
./manage.py shell
>>> HostCourse.objects.all().delete()
ManyToManyField 创建了一个新的 table,所以您想先删除那里的所有对象。用户不会被删除
在 db_shell 你会做:
delete from courses_hostcourse_created_by;
delete from courses_hostcourse;
我有 2 个模型 User,这是 Django 的 auth_user,和 HostCourse,它与 User 有多对多的关系
class HostCourse(TimeStamped, models.Model):
created_by = models.ManyToManyField(User, blank=True)
...
我正在使用 Postgresql,我正在尝试从 dbshell 中删除 HostCourse 中的数据。
delete from courses_hostcourse;
当我从 HostCourse 中删除一些数据时,它会抛出以下错误:
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"
如果我包含 on_delete=models.CASCASE
,是否还会删除相应 HostCourse 的用户?如果是,我如何找到解决方法,以便删除课程而不是用户?
通常你会在 python shell 中这样做:
./manage.py shell
>>> HostCourse.objects.all().delete()
ManyToManyField 创建了一个新的 table,所以您想先删除那里的所有对象。用户不会被删除 在 db_shell 你会做:
delete from courses_hostcourse_created_by;
delete from courses_hostcourse;