【问题标题】:Django Delete a many to many fieldDjango删除多对多字段
【发布时间】:2021-11-19 13:46:19
【问题描述】:

我有 2 个模型 User 是 Django 的 auth_user,以及 HostCourse 与 User 有多对多关系

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

我正在使用 Postgresql,我正在尝试从 dbshel​​l 中删除 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 的用户?如果是,我如何找到解决方法,以便删除课程而不是用户?

【问题讨论】:

    标签: django postgresql django-models many-to-many


    【解决方案1】:

    通常你会在 python shell 中这样做:

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

    ManyToManyField 创建一个新表,因此您想先删除那里的所有对象。用户不会被删除 在 db_shell 你会这样做:

    delete from courses_hostcourse_created_by;
    delete from courses_hostcourse;
    

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2015-08-22
      • 1970-01-01
      • 2011-02-05
      • 2021-11-20
      • 2016-02-23
      • 2020-10-28
      • 2020-03-16
      相关资源
      最近更新 更多