【问题标题】:Django "on_delete=models.CASCADE" not working in 2.0?Django“on_delete=models.CASCADE”在 2.0 中不起作用?
【发布时间】:2018-04-05 06:43:23
【问题描述】:

我正在尝试使用 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 行

【问题讨论】:

  • 这从来没有奏效(它没有真正的意义)。你确定你不想要OneToManyField

标签: python django


【解决方案1】:

我认为您误解了多对多关系的性质。

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

on_delete 仅适用于标准 OneToOneFieldOneToManyField

【讨论】:

    【解决方案2】:

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

    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()   
    

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2018-11-03
      • 2017-06-22
      • 2020-07-10
      • 2020-11-08
      • 2016-06-17
      • 1970-01-01
      • 2019-06-11
      • 2011-06-16
      相关资源
      最近更新 更多