我有两个模型:广告和横幅
当我使用“通用视图”时DetailView如何同时带两个模型下面的代码只带来一个广告
我的url.py
url(r'^(?P<pk>\d+)/$', DetailView.as_view(
model = Advertisment,
context_object_name = 'advertisment',
), name='cars-advertisment-detail'),
答案 0 :(得分:7)
当然,只需覆盖get_context_data
即可向上下文添加内容。
path('<int:pk>/', YourDetailView.as_view(), name='cars-advertisment-detail'),
class YourDetailView(DetailView):
context_object_name = 'advertisment'
model = Advertisement
def get_context_data(self, **kwargs):
"""
This has been overridden to add `car` to the template context,
now you can use {{ car }} within the template
"""
context = super().get_context_data(**kwargs)
context['car'] = Car.objects.get(registration='DK52 WLG')
return context
答案 1 :(得分:4)
对我来说,制作这样的自定义mixin更容易:
class ExtraContextMixin(object):
def get_context_data(self, **kwargs):
context = super(ExtraContextMixin, self).get_context_data(**kwargs)
context.update(self.extra())
return context
def extra(self):
return dict()
稍后您可以将此mixin子类化,然后覆盖extra
,如下所示:
class MyDetailView(ExtraContextMixin, DetailView):
def extra(self):
extra = Extra.objects.all()
return dict(extra = extra)
我认为这是更清洁而不是覆盖get_context_data