Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!