Pablo Estrada
Pablo Estrada

Reputation: 3452

Getting the count of a Filtered Result in a template on Django

Im trying to access a related model on the template like this:

course.course_set.all.0.section_set.all.0.student_assignation.count

The problem is that I would like to count all the student assignations which have an active = True property.

I would like to be able to do something like this:

course.course_set.all.0.section_set.all.0.student_assignation(active=True).count

How can I accomplish this on the django template?

Upvotes: 0

Views: 206

Answers (2)

RemcoGerlich
RemcoGerlich

Reputation: 31260

You have far too much logic in the template. Create a method on one of your model classes that actually returns the number you want; I'd propose one, but it's too unclear what you're doing (why the .all.0, aren't the other results important? Why course.course_set, is that a many to many to itself?). What are your models like?

How would you describe what you are displaying in English? That probably gives a hint to what kind of method you should create.

Upvotes: 0

karthikr
karthikr

Reputation: 99620

Django templates are note meant for such complex queries. There are a few ways you can handle this

One, create a custom django template tag

Two, create a class method which would provide this info.

Example

class Course:
    ...
    def sutdent_assign_count(self):
        #Your query goes here..

Upvotes: 1

Related Questions