尝试创建 Django 迁移时,ForeignKey 缺少必需的位置参数 on_delete
Posted
技术标签:
【中文标题】尝试创建 Django 迁移时,ForeignKey 缺少必需的位置参数 on_delete【英文标题】:ForeignKey missing required positional argument on_delete when trying to create a Django migration 【发布时间】:2018-11-09 00:41:01 【问题描述】:我正在尝试使用 python/django 和 postgres 创建表。我为models.py
中的每个数据库表创建类。当我尝试创建迁移时,它给了我这个错误:
File "..\database\models.py", line 40, in <module>
class group(models.Model):
File "database\models.py", line 41, in group
user_id = models.ForeignKey(user) TypeError: __init__() missing 1 required positional argument: 'on_delete'
这是我的代码
class user(models.Model):
STATUS_CHOICES = (
('active','Active'),
('not active', 'Not active')
)
user_id= models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=70, null=True, blank=True, unique=True)
phone = models.CharField( max_length=17, blank=True)
gender = models.CharField(max_length=50)
region = models.CharField(max_length=50)
password = models.CharField(widget=models.PasswordInput)
active = models.CharField(max_length=50, choices=STATUS_CHOICES, default='not active')
register_date = models.DateField(default=date.today)
def _str_(self):
return self.user_id
class train(models.Model):
train_CHOICES = (
('intercity', 'Intercity'),
('sprinter', 'Sprinter')
)
train_id= models.AutoField(primary_key=True)
train_type = models.CharField(max_length=50, choices=train_CHOICES, default='intercity')
def _str_(self):
return self.train_id
class group(models.Model):
user_id = models.ForeignKey(user)
group_id = models.AutoField(primary_key=True)
trip_id = models.ForeignKey(trip)
created_date = models.DateField(default=date.today)
started_at = models.DateTimeField()
def _str_(self):
return self.group_id
我对 Python 真的很陌生。我认为有很多错误。能给个提示吗?
【问题讨论】:
【参考方案1】:由于 Django 2.0,on_delete
是 ForeignKey
的必需参数(在旧版本中默认为 CASCADE),您应该为所有 ForeignKey
字段添加它:
user_id = models.ForeignKey(user, on_delete=models.CASCADE)
trip_id = models.ForeignKey(trip, on_delete=models.CASCADE)
注意on_delete=models.CASCADE
表示在删除用户或行程对象时,Django 会删除包含 ForeignKey 的对象。您可以找到其他选项列表here。
【讨论】:
以上是关于尝试创建 Django 迁移时,ForeignKey 缺少必需的位置参数 on_delete的主要内容,如果未能解决你的问题,请参考以下文章