在尝试创建Django迁移时,ForeignKey缺少必需的位置参数on_delete

时间:2018-05-30 08:31:15

标签: python django database postgresql django-migrations

我正在尝试使用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 个答案:

答案 0 :(得分:7)

on_deleteForeignKey的必填参数,您应该为所有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