B
B
bubublik2019-02-23 13:09:45
Django
bubublik, 2019-02-23 13:09:45

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()

As you can see, the connection between them is not required. But if necessary, it can be.
The problem occurs when deleting a Live object, if it has a link to a Target.
I tried to delete using the usual delete:
obj.delete()
An error occurs
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"

Clearly, the integrity error is due to the presence of a non-remote link.
Solved it like this:
obj.targets.clear()
obj.delete()

But maybe there is a more beautiful or correct method so that when deleting, the links from the intermediate table are immediately deleted?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2019-02-25
@tumbler

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 question

Ask a Question

731 491 924 answers to any question