In SQL, this would be (and I'm winging this right now so I might be
slightly off)
SELECT name, address, `date`, test_name, grade
FROM Student as stu
LEFT JOIN Grade ON stu.id = Grade.student_id
WHERE `date` >=
(SELECT max(`date`) FROM Grade WHERE student_id = stu.id)
ORDER BY name
Unless you have an extremely large amount of students you're filtering
on I'd use the following:
for s in Students.objects.order_by('name'):
grades = Grade.objects.filter(student_id=s.id).order_by('-date')[:
1]
if len(grades) > 0:
# use the grades object to print the latest grade
pass
else:
# there is no grade for this student
pass
I'd have to investigate whether the ORM will optimize this, but I
doubt it does (currently). It's possible there is a better way, but I
don't know of one without resorting to SQL.
On Jan 28, 1:57 pm, Michael Shepanski <[email protected]> wrote:
> Is it possible to code this scenario using the Django ORM?
>
> I have two tables:
> STUDENT: id, name, address
> GRADES: id, student_id, date, test_name, grade
>
> Each Student will have several entries in the Grades table. I am
> wondering if it is possible using Django's ORM to select all students
> along with their *latest* grade information. I basically want a result
> table that looks like the following, where date, test_name, and grade
> are for the latest result (by date).
>
> LATEST_GRADES: id, name, address, date, test_name, grade
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.