Problem statement
Students can take many courses, courses have many students, and each student has at most one transcript. app/models.py defines the three models, but nothing links them yet. Your task is to add the missing relationships, choosing the right relationship type for each.
Existing Models
app/models.py already defines all three models:
| Model | Field | Meaning |
|---|---|---|
| Course | code | short text, at most 20 characters, never shared |
| Course | title | text, at most 200 characters |
| Student | name | text, at most 200 characters |
| Student | an email address, never shared | |
| Transcript | gpa | a grade point average such as 3.50 (two decimal places) |
Nothing connects them yet. The two links are what you add, at the # Write your code here markers.
Requirements
- Enrollment: many students per course, many courses per student. Add a courses field to Student (declared on Student, not on Course). A student can be enrolled in many courses and a course can hold many students. Enrolling a pair links them on both sides; removing an enrollment unlinks them on both sides.
- Enrollment is readable from either side. student.courses.all() returns the student's courses and course.students.all() returns the course's students. The reverse name students must belong to the relationship itself (a hand-written property does not count), and the Django default course.student_set must not exist.
- At most one transcript per student, enforced by the database. Add a student field to Transcript. A second transcript for the same student must be rejected with an IntegrityError. Deleting a student deletes their transcript.
- The transcript is a single object from either side. transcript.student returns the owning student, and student.transcript returns that student's transcript itself (an object with a gpa), not a collection of transcripts. Accessing it on a student who has none raises Student.transcript.RelatedObjectDoesNotExist.
Sample Usage
>>> alice = Student.objects.create(name="Alice", email="alice@example.com")
>>> algebra = Course.objects.create(code="MATH101", title="Algebra")
>>> alice.courses.add(algebra)
>>> list(algebra.students.values_list("name", flat=True))
['Alice']
>>> alice.courses.remove(algebra)
>>> list(algebra.students.all())
[]
>>> alice.transcript
Traceback (most recent call last):
...
app.models.Student.transcript.RelatedObjectDoesNotExist: Student has no transcript.
>>> Transcript.objects.create(student=alice, gpa=Decimal("3.50"))
>>> Student.objects.get(pk=alice.pk).transcript.gpa
Decimal('3.50')
>>> Transcript.objects.create(student=alice, gpa=Decimal("2.00"))
Traceback (most recent call last):
...
django.db.utils.IntegrityError: UNIQUE constraint failed: app_transcript.student_id
