it isn’t possible to call a model’s methods in a template without making your own template method. Hence, to show, say, the number of upvotes for a comment:
comment.rating_set.filter(vote=1).count()
each comment, before it is sent to the template, has a rating_set member added to it like so:
comment.rating_set = comment.rating_set.filter(vote=1).count()
simple enough, however there are several ways for a comment to be retrieved (that is, several methods that are used to get a comment, depending on the situation). The template is constantly used.
For each method, its possible to alter it so instead of:
return commentList
it reads
return addInVotes(commentList)
where addInVotes is just a simple function that loops through each comment in the list, and then runs the above code to add the rating_count value.
the question here then is this – instead of adding this across all the methods, is it possible to “attach” the code to model.get and model.filter? I’m aware i can extend the Model for the comment to have a newly defined filter and get, but is there any other way? It seems like the kind of thing dJango would have hidden away somewhere.
Take a look at the Manager object. You can create a subclass of the default manager with additional methods that do common filtering, in one place, instead of in every view.