Django 添加不可空字段(ForeignKey)

Django add non-nullable field (ForeignKey)

我需要将 ForeignKey 字段添加到模型中,但是 makemigrations returns 错误以设置默认值。但是我不会任何默认值。

例如

@python_2_unicode_compatible
class Doctor(models.Model):
    name = models.CharField(max_length=250)
    surname = models.CharField(max_length=250)
    middlename = models.CharField(max_length=250)
    city = models.CharField(max_length=250)
    specialization = models.ForeignKey('Specialization', blank=True)

    def __str__(self):
        return "%s %s" % (self.name, self.surname)

@python_2_unicode_compatible
class Specialization(models.Model):
    name = models.CharField(max_length=250)
    #spec_table_name = models.ForeignKey('SpecializationTable')

    def __str__(self):
        return self.name

class Consultation(models.Model):
    client_id = models.ForeignKey('Client')
    doctor_id = models.ForeignKey('Doctor')

    #how to dropdown from doctor
    #record_id = models.ForeignKey(Specialization)

@python_2_unicode_compatible
class SpecializationTable(models.Model):
    name = models.CharField(max_length=250)

    def __str__(self):
        return self.name

class SpecializationTableRow(models.Model):
    row_name = models.CharField(max_length=250)
    row_description = models.CharField(max_length=999)
    row_required = models.BooleanField()
    table_name = models.ForeignKey(SpecializationTable)

这是我已有的模型,当我尝试在 Specialization 中取消注释 ForeignKey 时 - 出现错误。如果我删除所有迁移,并从头开始——就不会有错误。

而且-我根本没有记录(干净的数据库)。

如何传递此错误,而不是 drop\create 从头开始​​分贝?

从 django 的角度来看,问题在于它必须知道如何处理 Specialization 模型的现有记录。它不知道没有这些。

如果您有一个干净的数据库,正如您所说,您可以取消将迁移应用到创建相关模型的位置。假设 Specialization 是在名为 0003_* 的迁移中创建的,您可以调用:

> python manage.py migrate <app_name> 0002

那么您可以删除应用中从0003开始的所有迁移文件。然后,makemigrations 将再次起作用。如果它是在 0001 中创建的,您必须执行:

> python manage.py migrate <app_name> zero

也就是说,您在 makemigrations 期间提供的默认值不会以任何方式保留(它只会应用于 migrate 期间的现有记录)。因此,如果您有一个空数据库,则提供任何值(例如 1)都不会产生任何影响。