Answer the question
In order to leave comments, you need to log in
Correct way to delete objects in django when using many-to-many?
There are two models:
class Target(models.Model):
created_dt = models.DateTimeField(auto_now_add=True)
updated_dt = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='targets')
title = models.CharField(max_length=200)
live = models.ManyToManyField(LiveLot, related_name='targets', blank=True)
class Live(models.Model):
created_dt = models.DateTimeField(auto_now_add=True)
updated_dt = models.DateTimeField(auto_now=True)
closed_dt = models.DateTimeField()
obj.delete()
psycopg2.IntegrityError: update or delete on table "blabla" violates foreign key constraint "blablabla" on table "app_targe
t_lots"
DETAIL: Key (id)=(32845) is still referenced from table "app_target_live"
obj.targets.clear()
obj.delete()
Answer the question
In order to leave comments, you need to log in
There are no useful solutions on this topic on the Internet, although in my opinion there should be at least a paragraph in the Django documentation. One of the solutions is to make a through model in which to specify the cascade deletion explicitly in the ForeignKey description. But at the same time, M2M fields begin to behave a little differently (regarding the signals sent and the appearance in the admin panel). I would hang the m2m cleanup on pre_delete and not suffer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question