On Feb 4, 1:29 am, "R. K." <[EMAIL PROTECTED]> wrote:
> "posts = Post.objects.filter(topic__forum__name="myforumname") #
> double underscores in both spots "
> This works, but anyway, how can I get just the posts quantity for the
> specific forum, for example I have ten forums, and I can get number of
> posts for one or another or even for all of them, but another
> question, how to show this in template. Now I'm getting all forums
> from DB (forums = Forum.objects.all()) and passing that 'forums'
> object to template and in template I'm iterating through 'forums'
> objects. And I don't see any solution, of adding that posts number to
> 'forums' object.

Probably you'll want to write a custom something-or-other. There are a
couple of different ways to attack the problem. You could add a
post_count() method to the forum model, something that looked like:
def post_count(self):
    posts = 0
    for topic in self.topic_set.all():
        posts += topic.post_set.all().count()
    return posts

Which could be used in the template like so:
{% for forum in forums %}
    {{ forum.post_count }}
{% endfor %}

As for all posts in all forums, you might be able to add a class
method (one which doesn't take a 'self' argument) which gets all the
forums, all the topics in each forum, and adds up all the posts in
each topic, kind of an extended version of the above. But I'm not
certain that you could call that in a template - you'd want to
generate that number in the view, and pass it in as a separate
variable.

Another option would be a custom template tag:
http://www.djangoproject.com/documentation/templates_python/#writing-custom-template-tags
http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/

It wouldn't be hard to write a custom template tag that did all the
work of getting all the forums/topics/posts and adding them up. Once
you've made that, though, you might as well modify it so that it can
accept a single forum instance (ie, replacing the count_posts() method
above) as an argument, or a special keyword to return the number of
all posts in all forums. It could even accept topic instances, as
well. Then you've got one tool for all your post-counting needs.

The main point is, once you're doing calculations of any complexity at
all, the template is not the place to be doing them. Either do it in
the view and pass in new variables, or (preferably) write some
reusable custom code to keep things clean.

Hope that was helpful,
Eric
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to