tags:

views:

1718

answers:

4

I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.

{% for choice in choices %}
    {{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}

it raises an exception with this message "Could not parse the remainder" I googled it and so far no luck.

thanks in advance.

+2  A: 

You need to find (or define) a 'get' template tag, for example, here.

Ned Batchelder
+2  A: 

Ideally, you would create a method on the choice object that found itself in votes, or create a relationship between the models. A template tag that performed the dictionary lookup would work, too.

Jeff Ober
+9  A: 

To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:

    class Choice(models.Model):
        text = models.CharField(max_length=200) 

    def calculateVotes(self):
            return Vote.objects.filter(choice = self).count()

    votes = property(calculateVotes)

And then in your template, you can do:

    {% for choice in choices %}
            {{choice.choice}} - {{choice.votes}} <br />
    {% endfor %}

The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.

I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.

John Ewart
thanks @john ewart, your solution worked for me. I am newbie to django and python and can't figureout how to get the sql that ORM generated.
Mohamed
You can find the answer to that bit over here: http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-runningIt's quite simple, actually and can be displayed in your template, or logged with a logging facility, but you have to remember to turn DEBUG on for this to work.
John Ewart
+4  A: 

you can use the dot notation:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup (e.g., foo["bar"])
  • Attribute lookup (e.g., foo.bar)
  • Method call (e.g., foo.bar())
  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.

Wilhelm