Hahore-kun
Hahore-kun

Reputation: 17

Troubles with ForeignKey in Django

I have models like this:

class Subject(models.Model):
    name = models.CharField(unique=True, ...)

class Curriculum(models.Model):
    name = models.IntegerField(unique=True, ...)
    subjects = models.ManyToManyField(Subject)

class Grade(models.Model):
    name = models.CharField(unique=True,...)
    curriculum = models.ForeignKey(Curriculum, ...)

If I know name of specific instance of Grade, how I can get list of Subjects, which linked with Grade through Curriculum. I've tried something like the following:

curriculum = Grade(name=grade).curriculum
subjectsqueryset = curriculum.subjects

but received an exception

django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Grade has no curriculum.

What I'm doing wrong?

Upvotes: 0

Views: 381

Answers (3)

DJeanCar
DJeanCar

Reputation: 1593

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

Upvotes: 0

tjati
tjati

Reputation: 6089

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.

Upvotes: 0

ilse2005
ilse2005

Reputation: 11439

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.

Upvotes: 1

Related Questions