[Fixed]-Troubles with ForeignKey in Django

1👍

If you have a Grade object with known name in your database. Then you can filter using:

obj = Grade.objects.get(name=grade)
# access curriculum
obj.curriculum
# get subjects
obj.curriculum.subjects.all()

What you where doing is create an instance of Grade with name=grade. But this is not in the db yet and you didn’t set the curriculum attribute. That’s why you got the RelatedObjectDoesNotExist.

0👍

You can’t access your existing Grade with this line:

curriculum = Grade(name=grade).curriculum

You are creating a new Grade-object having name the value of grade. This is not what you want.

Use

my_grade = Grade.objects.get(name=grade)
my_grade.curriculum # or whatever ...

to work with an existing object.

If you want to create an new object you have to save it before accessing any related objects.

👤tjati

0👍

grade = Grade.objects.get(id=id) # grade instance
curriculum = grade.curriculum # curriculum is a Foreign Key
subjects = curriculum.subjects.all() # subjects is a ManyToManyField
for subject in subjects:
    print subject # each subject of curriculum

Leave a comment