TypeError: on_delete must be callable

*爱你&永不变心* 提交于 2020-05-29 05:27:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!