A
A
ANDREW_TUR2018-10-08 14:02:03
Django
ANDREW_TUR, 2018-10-08 14:02:03

Django. many-to-many. How to do a cascading delete from a link table?

Let's admit there are two tables and connecting between them...
5bbb384fb9c20489553268.png
How to make that at removal of entity "developer", record from the connecting table was deleted also???
What is the correct way to write this in Django? I understand it does not do this by default?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FulTupFul, 2018-10-08
@ANDREW_TUR

on_delete=models.CASCADE by default. In essence, manytomanyfield just behind the scenes creates another table with ForeignKey relationships for two tables, but no one forbids you to control this manually. Then be sure to include the through attribute in the ManyToManyField:

class M2M(models.Model):
    developer = models.ForeignKey('Developer', on_delete=models.CASCADE)
    project = models.ForeignKey('Project', on_delete=models.CASCADE)
    
    class Meta:
        db_table = "m2m"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question