尽管父键存在,为什么我的 FOREIGN KEY 约束会失败?

问题描述 投票:0回答:1

将 Excel 工作表与数据库同步:

for record in lesson_records:
    try:
        date = parser.parse(record['Date']).date()
        start_time = parser.parse(record['Start Time']).time()
        end_time = parser.parse(record['End Time']).time()

        primary_tutor = get_object_or_404(Staff, gmail=record['Primary Tutor Email'])
        logger.info(primary_tutor)
        course = get_object_or_404(Course, course_code=record['Course Code'])
        logger.info(course)

        lesson, created = Lesson.objects.update_or_create(
            lesson_code=record['Lesson Code'],
            defaults={
                'course_code': course,
                'date': date,
                'start_time': start_time,
                'end_time': end_time,
                'lesson_no': record['Lesson Number'],
                'school': record['School / Customer'],
                'teacher': record['Teacher'],
                'teacher_contact': record['Teacher Contact'],
                'venue': record['Venue'],
                'remarks': record['Remark'],
                'delivery_format': record['Delivery Format'],
                'primary_tutor': primary_tutor
            }
        )

        logger.info(record['Lesson Code'])
    except Exception as e:
        lesson_errors.append(f"Error in Lesson {record['Lesson Code']}: {str(e)}")
        logger.error(f"Error in {record['Lesson Code']}: {str(e)}")

我收到:

[课程代码]中的错误:FOREIGN KEY 约束失败

每门课程。

primary_tutor
course
已正确记录,因此
get_object_or_404
都成功并存在于数据库中,但仍然未通过外键约束。

型号:

class Lesson(models.Model):
    course_code = models.ForeignKey(Course, on_delete=models.CASCADE)
    date = models.DateField()
    start_time = models.TimeField()
    end_time = models.TimeField()
    lesson_no = models.IntegerField()
    lesson_code = models.CharField(max_length=20, primary_key=True)
    school = models.CharField(max_length=100)
    teacher = models.CharField(max_length=10)
    teacher_contact = models.CharField(max_length=100)
    teacher_email = models.EmailField(blank=True, null=True)
    venue = models.CharField(max_length=100)
    remarks = models.TextField(blank=True, null=True)
    delivery_format = models.CharField(max_length=10)
    primary_tutor = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name='primary_tutor')
    other_tutors = models.ManyToManyField(Staff)
    calender_id = models.CharField(max_length=100, blank=True, null=True)
    change = models.BooleanField(default=False)

我重置了数据库,再次执行了

makemigrations
migrate
,但仍然不起作用。

python django sqlite
1个回答
0
投票

默认情况下,Django 按照模型名称的字母顺序创建迁移文件。 在你的情况下,它的顺序是:课程,课程,然后是工作人员。 但是,当它在迁移课程模型时尝试创建与表 appname_staff 的关系时,它会失败,因为没有具有该名称的表。 因此,我建议您首先注释与内容模型相关的字段,然后进行迁移。之后,您应该取消注释这些行并进行与现有表的关系的迁移。

© www.soinside.com 2019 - 2024. All rights reserved.