0

I have 2 tables:

class Subject(models.Model):
    ....

class Season(models.Model):
    season = models.CharField(max_length=2, primary_key=True)
    subject = models.ManyToManyField(Subject)

When I delete a Subject instance, I want the Season instance that is related to delete as well. How do I do that in the models?

iscream
  • 680
  • 2
  • 8
  • 20
  • 2
    Does this answer your question? [Django - Cascade deletion in ManyToManyRelation](https://stackoverflow.com/questions/3937194/django-cascade-deletion-in-manytomanyrelation) – wfehr Apr 20 '20 at 12:16
  • No not really. The person who asked that question actually had to use a ForeignKey, OnetoMany relationship. In my case I have to use ManyToMany relationship – iscream Apr 20 '20 at 12:49

1 Answers1

1

If you really need a ManyToMany relation, then it implies that many Subjects may have many Seasons too.

And in a ManyToMany relation, links are stored in an intermediate table that stores IDs of both linked records.

If you delete a Subject or a Season, all the records related to the deleted item will be removed from the intermediate table automatically.

lbris
  • 1,068
  • 11
  • 34
  • So there is an intermediate table that will record the changes? If I update a Season, will the data in the original Subjects table change? Or will the intermediate table change only? – iscream Apr 20 '20 at 12:41
  • 1
    @iscream If you link a `Season` to a `Subject` (or vice versa), it will add a row in the intermediate table with following data : id of the row in this table, id of the `Season`, id of the `Subject`. Nothing more (except if you decide to do your own intermediate table, with the `through` attribute). The intermediate table only stores (in your case) "Which `Season` is linked to which `Subject`". So if you update a `Season` or a `Subject`, changes are only made in their respective tables – lbris Apr 20 '20 at 13:42