Django“on_delete = models.CASCADE”在2.0中不起作用?

时间:2018-04-05 06:43:24

标签: python django

我正在尝试使用on_delete = models.CASCADE创建一个简单的模型关系。
这是我的代码: -

class Answer_Options(models.Model):
    text = models.CharField(max_length=200)

class Quiz(models.Model):
    q_type = models.CharField(max_length=50)
    text = models.CharField(max_length=200)
    possible_answers = models.ManyToManyField(Answer_Options, on_delete=models.CASCADE)

在终端上给我以下错误: - TypeError:_init __()得到了一个意外的关键字参数'on_delete' 地点: - django \ db \ models \ fields \ related.py“,第1129行

2 个答案:

答案 0 :(得分:1)

我认为你误解了ManyToMany关系的本质。

在ManyToMany关系中删除相关模型时,不应删除一个模型。

on_delete仅适用于标准OneToOneFieldOneToManyField

答案 1 :(得分:0)

批量替换的简单脚本(注意!您必须测试输出数据!!!):

import os
import fileinput
from termcolor import colored
for dname, dirs, files in os.walk("apps"):
    for fname in files:
        fpath = os.path.join(dname, fname)
        if fname == 'models.py':
            output = []
            print fname
            with open(fpath) as f:
                lines = f.readlines()
                for line in lines:

                    if ('ForeignKey' in line) or ('OneToOneField' in line):
                        print colored(line,'yellow')
                        if 'GenericForeignKey' in line: 
                            output.append(line)
                        else:        
                            repl_line = line.rstrip()
                            if repl_line[-1] == ')' and not 'on_delete' in line:
                                if repl_line[-2] == ',':
                                    repl_line = '%s on_delete=models.CASCADE)\n' % repl_line[:-1]
                                elif repl_line[-3] == ',':
                                    '%son_delete=models.CASCADE)\n' % repl_line[:-1]     
                                else:
                                    repl_line = '%s, on_delete=models.CASCADE)\n' % repl_line[:-1]
                                print colored(repl_line,'green')    
                                output.append(repl_line)    
                            else:    
                                output.append(line)
                    else:
                        output.append(line)   


            f.close()
            f = open(fpath,"w")
            f.write(''.join(output))
            f.close()