Is there a way to pass an object to the template and have the template handle all of the attributes without hardcoding them into the template?
On Jul 3, 10:04 am, Rajesh D <rajesh.dha...@gmail.com> wrote: > On Jul 3, 9:17 am, Nikola Pavlović <n...@datasnok.org> wrote: > > > > > > > Hello people, > > > I'm writing my first Django application and would like to know what is > > considered more efficient: getting values of models' attributes in views > > or directly in templates? > > > More precicely, say we have a Person model with name and id attributes, > > and these need to be shown on a page. > > > Is it better for a view to "prepare" a context like this: > > > # views.py > > # ... > > > persons = [] > > > for person in Person.objects.all(): > > persons.append({'id': person.id, 'name': person.name}) > > > return render_to_response('some_template.html', persons) > > > # some_template.html > > > {% for p in persons %} > > Id: {{ p.id }}; Name: {{ p.name }} > > {% endfor %} > > > or just pass a QuerySet in a context like this: > > # views.py > > # ... > > > persons = Person.objects.all() > > return render_to_response('some_template.html', persons) > > > and then let the template access attribute values directly? > > > Does it make a difference in terms of performance? > > The second method avoids an extra loop and also keeps your code leaner > (less code == lesser chances of bugs). It's also the more commonly > used method. And if you are displaying just a handful of persons per > page, the performance differences should be negligible either way. If > you have a lot of persons in that query set, you will want to use some > kind of pagination anyway. > > -RD --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---