Reputation: 1756
I am trying to create a simple model relationship with on_delete=models.CASCADE.
Here is my code:-
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)
It is giving me the following error on terminal:-
TypeError: _init__() got an unexpected keyword argument 'on_delete'
Location:- django\db\models\fields\related.py", line 1129
Upvotes: 2
Views: 3045
Reputation: 1
Simple script for Mass replace (NOTE! You must test output data!!!):
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()
Upvotes: 0
Reputation: 13047
I think you are misunderstanding the nature of a ManyToMany relationship.
One model should not get deleted on deleting of the related model in ManyToMany relationship.
on_delete
is only available with the standard OneToOneField
and OneToManyField
.
Upvotes: 5