3👍
✅
Why not use a dictionary?
newthing = {}
newthing['your_key'] = to_add
In the template, you can access dictionary values with:
{{newthing.your_key}}
Or use the for loop if you have a dictionary of dictionaries
41👍
You can set anything on a python object:
for obj in self.model.objects.all() :
obj.score = total_score / total_posts
This will work even if obj does not have a score attribute. In the template request it like so:
{{ obj.score }}
Yes, it’s that simple.
However, if the calculations you’re doing can be done in the database, you should look into annotate.
- Simple tutorial for Neo4J and using it with django + python
- Upgrading to Django 1.7. Getting error: Cannot serialize: <storages.backends.s3boto.S3BotoStorage object
- How to print pretty JSON on a html page from a django template?
- ImportError: No module named mysite.settings (Django)
1👍
If @Melvyn’s solution doesnt work for you:
Ensure you don’t call .all()
etc on the queryset when modifying the queryset, as .all()
returns a copy of the queryset, e.g.
qs = foo.objects.filter(bar=1);
for obj in qs.all():
obj.caz = 1; # Will not persist
Now qs
will remain unchanged.
Rather:
qs = foo.objects.filter(bar=1).all();
for obj in qs:
obj.caz = 1;
Now you can access .caz
in the template.
- How to set dynamic page_size in DRF PageNumberPagination
- How to send success message if we use django generic views
- Django Admin: has_delete_permission Ignored for "Delete" Action
- How to point correctly to static image in django
Source:stackexchange.com