可以使用什么代替on_delete CASCADE

时间:2022-02-17 02:54:40

I created a books app, It has Publisher and Books models. In books Model, I assigned a foreignkey for Publisher using on_delete=models.CASCADE. Actually I don't want to use this on_delete function, because if I delete data from parent table it will delete data on child table also. But I am getting:

我创建了一个书籍应用程序,它有Publisher和Books模型。在Books Model中,我使用on_delete = models.CASCADE为Publisher分配了一个外键。实际上我不想使用这个on_delete函数,因为如果我从父表中删除数据,它也会删除子表上的数据。但我得到:

TypeError: init() missing 1 required positional argument: 'on_delete'

TypeError:init()缺少1个必需的位置参数:'on_delete'

If I don't use on_delete = models.CASCADE.

如果我不使用on_delete = models.CASCADE。

Model:

class Book(models.Model): 
    title = models.CharField(max_length = 30) 
    authors = models.ManyToManyField(Author) 
    publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE) 
    publication_date = models.DateField() 

    def __str__(self): 
        return self.title

2 个解决方案

#1


0  

As of Django 2.0 the on_delete is required. There are several options you can provide for on_delete, they are detailed here.

从Django 2.0开始,on_delete是必需的。您可以为on_delete提供多个选项,详细信息请参见此处。

#2


0  

It is mandatory to add on_delete function from Django V2.0, So you can set (tablename, on_delete = SET_NULL, blank = True, null = True). if u don't want to delete data from child table when parent data is deleted.

必须从Django V2.0添加on_delete函数,所以你可以设置(tablename,on_delete = SET_NULL,blank = True,null = True)。如果您不想删除父数据时从子表中删除数据。

publisher = models.ForeignKey(Publisher, models.SET_NULL, blank = True, null = True)

publisher = models.ForeignKey(Publisher,models.SET_NULL,blank = True,null = True)

#1


0  

As of Django 2.0 the on_delete is required. There are several options you can provide for on_delete, they are detailed here.

从Django 2.0开始,on_delete是必需的。您可以为on_delete提供多个选项,详细信息请参见此处。

#2


0  

It is mandatory to add on_delete function from Django V2.0, So you can set (tablename, on_delete = SET_NULL, blank = True, null = True). if u don't want to delete data from child table when parent data is deleted.

必须从Django V2.0添加on_delete函数,所以你可以设置(tablename,on_delete = SET_NULL,blank = True,null = True)。如果您不想删除父数据时从子表中删除数据。

publisher = models.ForeignKey(Publisher, models.SET_NULL, blank = True, null = True)

publisher = models.ForeignKey(Publisher,models.SET_NULL,blank = True,null = True)