Forgive my ignorance here but i have been scratching my head for several hours at this point.
i have some related models.
class Course(models.Model):
name = models.CharField(max_length=100)
class ClassMeeting(models.Model):
course = models.ForeignKey(Course, related_name='meetings', on_delete=models.CASCADE)
# day of week and time i.e "wednesdays at 4pm".
class Class(models.Model):
course = models.ForeignKey(Course, related_name='classes', on_delete=models.CASCADE)
class_meeting = models.ForeignKey(ClassMeeting, on_delete=models.CASCADE)
class_date = models.DateField()
# this is the actual day a class occurs "jan 8th"
someone signs up for Physics Wed @ 6pm
but the actual classes become 'jan 1st' , 'jan 8th', etc...
to create the courses and their related class schedules for each semester i have a CourseAdmin with two inlines one for ClassMeetings and one for Classes
the ClassMeetingInline does not cause any issues, only like 1 or 2 extra queries.
however the ClassInline is causing an N+1 and i don’t know how to stop it.
the N+1 occurs when i add the ‘class_meeting’ field to the inline form. without this field it does not happen, and the queries are all for fetching ClassMeeting data.
I am not sure where to put the prefetch_related so django can find the info it needs in the queryset.
i believe there is a get_queryset
on both the CourseAdmin
and the ClassInline
i have tried adding prefetch_related("meetings")
to the CourseAdmin and prefetch_related("class_meeting")
to the ClassInline
.
i have also tried adding prefetch_related("classes__class_meeting")
to the CourseAdmin
i’ve tried a few GPT solutions, that obviously didn’t work otherwise i wouldn’t be here, which had to do with overriding get_formset
and others.
i am using debug toolbar, and i have commented out all my __str__()
methods to make sure it is not coming from those.
it’s a bit of a weird one because the relationship is a bit circular.
any advice would be appreciated.
thanks.