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.
- Django Celery how to configure queues and see them in rabbitmq admin dashboard
- Pass form name variable into url in django
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
- Why is a formfield's errors a list in Django?
- Django filter object with list of values
- Dynamically created accordions not functioning correctly in Django/python/html project
Source:stackexchange.com