本文介绍了django - DetailView如何同时显示两个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:广告和横幅

I have two models : Advertisment and Banner

当我使用通用视图DetailView如何同时带来两个模型下面的代码只带一个广告

when I using "generic view" DetailView How can I Bring two models at the same time The code below bring only one Advertisment

我的url.py

url(r'^(?P<pk>\d+)/$', DetailView.as_view(
    model               = Advertisment,
    context_object_name = 'advertisment',
), name='cars-advertisment-detail'),


推荐答案

当然,只要覆盖 get_context_data 将内容添加到上下文中。

Sure, just override get_context_data to add stuff to the context.

url(r'^(?P<pk>\d+)/$', 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 templates context,
        so you can use {{ car }} etc. within the template
        """
        context = super(YourDetailView, self).get_context_data(**kwargs)
        context["car"] = Car.objects.get(registration="DK52 WLG")
        return context

这篇关于django - DetailView如何同时显示两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 05:51