汎用ビューでdirect_to_templateを使う場合に、extra_contextを使うとする。
from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from projects.models import Project from presentation.models import Presentation from documents.models import Document info_dict = {'template': 'index.html', 'extra_context': {'project_list': Project.objects.filter(published=True), 'presentation_list': Presentation.objects.filter(published=True), 'document_list': Document.objects.filter(published=True)} } urlpatterns = patterns('', url(r'^$', direct_to_template, kwargs=info_dict, name='site_index'), (r'^admin/', include('django.contrib.admin.urls')), )
extra_contextはキャッシュされるので、このように書くとQuerySetはアクセス毎に評価されない。
lambdaを使うなどして、遅延評価させる必要があるらしい。
以下のようにした。
from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from projects.models import Project from presentation.models import Presentation from documents.models import Document info_dict = {'template': 'index.html', 'extra_context': {'project_list': lambda :Project.objects.filter(published=True), 'presentation_list': lambda :Presentation.objects.filter(published=True), 'document_list': lambda :Document.objects.filter(published=True)} } urlpatterns = patterns('', url(r'^$', direct_to_template, kwargs=info_dict, name='site_index'), (r'^admin/', include('django.contrib.admin.urls')), )