我想迁移一些模型,但是具有外键功能的模型会引起一些问题。
我运行了以下代码,并导致了错误
python manage.py migrate
外键似乎是问题
class Webpage(models.Model):
topic =models.ForeignKey(Topic)
name = models.CharField(max_length=264 , unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
Traceback (most recent call last):
File "C:\Users\helin\Anaconda3\envs\myenv\lib\sitepackages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs)
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)()
File "C:\Users\helin\Anaconda3\envs\myenv\lib\sitepackages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs)
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\helin\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 985, in _gcd_import
File "<frozen importlib._bootstrap>", line 968, in _find_and_load
File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 697, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\helin\Downloads\my_django\first_project\first_app\models.py", line 12, in <module>
class Webpage(models.Model):
File "C:\Users\helin\Downloads\my_django\first_project\first_app\models.py", line 13, in Webpage
topic =models.ForeignKey(Topic)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
答案 0 :(得分:0)
是的,您缺少1个必需的位置参数:'on_delete'。
使用外键时,需要向其传递“ on_delete”参数。这样可以确保每当删除此外键为其主键的表/记录时,它将自动删除/保护用作外键的表的记录。
示例:
class Customer(models.Model):
customer_id = <something>
class Account(models.Model):
customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE)
因此,当在与客户相关的表中删除具有customer_id = x的客户时,它将删除“帐户”表中的相应记录。
您可以阅读here