[Answer]-Django getting related foreignkey fields confusion

1๐Ÿ‘

โœ…

As @DanielRoseman said, you really need to show your models. But it sounds like your confusion is rooted in having both a ManyToManyField between Course and College, and a separate College_Specific_Course_Details table. If Iโ€™m understanding you correctly, these are redundant. Instead, make College_Specific_Course_Details your M2M table by using the through keyword.

It might look something like this:

class Course(models.Model):
    # some fields

class College(models.Model):
    # some fields
    courses = models.ManyToManyField(Course, 
                                     through='CollegeCourse', 
                                     related_name='colleges')

class CollegeCourse(models.Model)
    college = models.ForeignKey(College, related_name='college_courses')
    course = models.ForeignKey(Course, related_name='college_courses')
    fee = models.IntegerField()

Then you can iterate like so:

{% for college_course in college.college_courses.all %} 
    {{ college_course.course.id }}
    {{ college_course.fee }}
{% endfor %}

0๐Ÿ‘

Ok keep many to many field relation as you wish :).
Just loop over CollegeSpecificCourseDetails object to get college,course and fees

college_course = CollegeSpecificCourseDetails.objects.all()
for college_course_detail in college_course:
    college = College.objects.filter(id=college_course_detail.college_id)
    course = Course.objects.filter(id=college_course_detail.course_id)
    fee = college_course_detail.monthly_fee
๐Ÿ‘คhemraj

Leave a comment