Django - Cascade deletion in ManyToManyRelation

前端 未结 4 581
陌清茗
陌清茗 2020-11-29 10:23

Using the following related models (one blog entry can have multiple revisions):

class BlogEntryRevision(models.Model):
    revisionNumber = models.IntegerFi         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 10:52

    I think you are misunderstanding the nature of a ManyToMany relationship. You talk about "the corresponding BlogEntry" being deleted. But the whole point of a ManyToMany is that each BlogEntryRevision has multiple BlogEntries related to it. (And, of course, each BlogEntry has multiple BlogEntryRevisions, but you know that already.)

    From the names you have used, and the fact that you want this deletion cascade functionality, I think you would be better off with a standard ForeignKey from BlogEntryRevision to BlogEntry. As long as you don't set null=True on that ForeignKey, deletions will cascade - when the BlogEntry is deleted, all Revisions will be too.

    As Of Django 2.0

    The ForeignKey initializer now requires you to specify the on_delete parameter:

    from django.db import models
    from .models import MyRelatedModel
    
    
    class model(models.Model):
        related_model = models.ForeignKey(MyRelatedModel, on_delete=models.CASCADE)
    

提交回复
热议问题