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.
kwutzee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.