Why does my FOREIGN KEY constraint fail despite parent key’s existence?

Syncing an Excel sheet with the database:

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)}")

I receive:

Error in [course code]: FOREIGN KEY constraint failed

for every course. primary_tutor and course are correctly logged so both get_object_or_404 succeeded and exist in the database, but it still failed the foreign key constraint.

Model:

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)

I resetted the database, did makemigrations and migrate again but it still doesn’t work.

0

By default Django makes migration files in alphabetical order of model names.
In your case it would be in order : Course, Lesson and then Staff.
But when it tries to create relation to table appname_staff when making migration for Lesson model it fails because there is no table with such name.
So, i recommend you to firstly comment fields where you relating to stuff model, then make migrations. after that you should uncomment those lines and make migrations with relations to EXISTING table.

New contributor

kwutzee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật