问题
Suddenly I am getting an error saying TypeError: on_delete must be callable.
I don't know how to solve this error as I don't see field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'),
mentioned anywhere in my code.
File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 6, in <module>
class Migration(migrations.Migration):
File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 47, in Migration
field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'),
File "/home/arch/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in __init__
raise TypeError('on_delete must be callable.')
TypeError: on_delete must be callable.
回答1:
A field in one of your models has:
class SomeModel(models.Model):
# …
field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category')
but you can not pass a string to on_delete=…
parameter, it should be:
class SomeModel(models.Model):
# …
field=models.ForeignKey(default=1, on_delete=models.CASCADE, to='main.Category')
You will need to remove the migration file (main/migrations/0014_auto_20191025_1154.py
) as well, and make new migrations.
回答2:
According to django docs, the on_delete
argument must be a callable, not a string.
Here's the CASCADE
callable defined in django.db.models
:
def CASCADE(collector, field, sub_objs, using):
collector.collect(sub_objs, source=field.remote_field.model,
source_attr=field.name, nullable=field.null)
if field.null and not connections[using].features.can_defer_constraint_checks:
collector.add_field_update(field, None, sub_objs)
来源:https://stackoverflow.com/questions/59272494/typeerror-on-delete-must-be-callable