Fetch data using foreign key

How to access semester attribute in the get query
Models.py

class Semester(models.Model):
    semId=models.IntegerField(unique=True)
    session=models.DecimalField(max_digits=4,decimal_places=0,null=True)
    def __str__(self):
        return str(self.semId)
class Course(models.Model):
    course=models.Manager()
    semester=models.ForeignKey(Semester,on_delete=models.CASCADE,null=True)
    courseName=models.CharField(max_length=100)
    courseId=models.IntegerField(unique=True)
    student=models.ManyToManyField(Student)
    def __str__(self):
        return str(self.courseName)

Views.py

def sem(request,id):
    ob=Course.course.get(semester=id)
    for o in ob:
        print(o.semester)
    return render(request,'sem.html')

Please do not post images of code here - they can’t be searched, or quoted in replies.

Copy/paste your actual code into the body of your message, surrounded by lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted, which is critical with python.

(Side note: This applies to your other topic as well)

1 Like

The get method does not return a queryset, it returns an instance of the model. There’s nothing to iterate over in your code - you access the member variable directly.