68๐
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.
351๐
choices = {'key1':'val1', 'key2':'val2'}
Hereโs the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
Basically, .items
is a Django keyword that splits a dictionary into a list of (key, value)
pairs, much like the Python method .items()
. This enables iteration over a dictionary in a Django template.
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-How do I make many-to-many field optional in Django?
- [Django]-What is actually assertEquals in Python?
230๐
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.
- [Django]-How do I run tests for all my Django apps only?
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-ImportError: No module named 'django.core.urlresolvers'
39๐
You need to find (or define) a โgetโ template tag, for example, here.
The tag definition:
@register.filter
def hash(h, key):
return h[key]
And itโs used like:
{% for o in objects %}
<li>{{ dictionary|hash:o.id }}</li>
{% endfor %}
- [Django]-How to use "get_or_create()" in Django?
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
- [Django]-Execute code when Django starts ONCE only?
10๐
django_template_filter
filter name get_value_from_dict
{{ your_dict|get_value_from_dict:your_key }}
- [Django]-Django-social-auth django-registration and django-profiles โ together
- [Django]-How to pass django rest framework response to html?
- [Django]-Django model constraint for related objects
8๐
Similar to the answer by @russian_spy :
<ul>
{% for choice in choices.items %}
<li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>
This might be suitable for breaking down more complex dictionaries.
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
4๐
Could find nothing simpler and better than this solution. Also see the doc.
@register.filter
def dictitem(dictionary, key):
return dictionary.get(key)
But thereโs a problem (also discussed here) that the returned item is an object and I need to reference a field of this object. Expressions like {{ (schema_dict|dictitem:schema_code).name }}
are not supported, so the only solution I found was:
{% with schema=schema_dict|dictitem:schema_code %}
<p>Selected schema: {{ schema.name }}</p>
{% endwith %}
UPDATE:
@register.filter
def member(obj, name):
return getattr(obj, name, None)
So no need for a with
tag:
{{ schema_dict|dictitem:schema_code|member:'name' }}
- [Django]-Automatic creation date for Django model form objects
- [Django]-Cannot set Django to work with smtp.gmail.com
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?
3๐
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.
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-How to completely dump the data for Django-CMS
- [Django]-PyCharm: DJANGO_SETTINGS_MODULE is undefined
-4๐
You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of
person = {'name': 'John', 'age': 14}
โฆdo:
from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'
This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.
- [Django]-Update all models at once in Django
- [Django]-How to monkey patch Django?
- [Django]-Django: how save bytes object to models.FileField?