我有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中删除一些数据时,它会抛出以下错误:
错误:表“courses_hostcourse”上的更新或删除违反了表“courses_hostcourse_created_by”上的外键约束“courses_hostcourse_c_hostcourse_id_ec1070c3_fk_courses_h”
如果我添加on_delete=models.CASCASE
,它是否也会删除相应HostCourse的用户?如果是,我怎样才能找到解决方法,以便它删除类(class)而不是用户?
最佳答案
通常你会在 python shell 中这样做:
./manage.py shell
>>> HostCourse.objects.all().delete()
ManyToManyField 创建一个新表,因此您需要先删除其中的所有对象。用户不会被删除 在 db_shell 中你会这样做:
delete from courses_hostcourse_created_by;
delete from courses_hostcourse;
关于Django 删除多对多字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69346112/