本文介绍了Django 将多个模型传递给一个模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个地址簿,其中包含条目之间的关系等.我有针对个人、公司、场所和角色的单独模型.在我的索引页面上,我想列出每个模型的所有实例,然后过滤它们.以便人们可以轻松搜索并找到条目.我已经能够使用通用视图列出单个模型并使用 get_extra_context 显示更多模型:

I am building an address book that includes the relationships between entries, etc. I have separate models for Individuals, Companies, Venues, and Roles. On my index page I would like to list all of the instances of each model and then filter them. So that a person could easily search and find an entry. I have been able to list a single model using generic views and use get_extra_context to show one more model:

#views.py

 class IndividualListView(ListView):

    context_object_name = "individual_list"
    queryset = Individual.objects.all()
    template_name='contacts/individuals/individual_list.html'


class IndividualDetailView(DetailView):

    context_object_name = 'individual_detail'
    queryset = Individual.objects.all()
    template_name='contacts/individuals/individual_details.html'

    def get_context_data(self, **kwargs):
        context = super(IndividualDetailView, self).get_context_data(**kwargs)
        context['role'] = Role.objects.all()
        return context

我还可以使用自定义视图列出单个模型:

I am also able to list a single model using a custom view:

#views.py
def object_list(request, model):
    obj_list = model.objects.all()
    template_name = 'contacts/index.html'
    return render_to_response(template_name, {'object_list': obj_list})

以下是这两个测试的 urls.py:

Here are the urls.py for both of these tests:

(r'^$', views.object_list, {'model' : models.Individual}),

(r'^individuals/$',
    IndividualListView.as_view(),
        ),
(r'^individuals/(?P<pk>d+)/$',
    IndividualDetailView.as_view(),

         ),

所以我的问题是我如何修改它以将多个模型传递给模板?"甚至有可能吗?StackOverflow 上的所有类似问题都只询问两个模型(可以使用 get_extra_context 解决).

So my question is "How do I modify this to pass more then one model to the template?" Is it even possible? All of the similar questions on StackOverflow only ask about two models (which can be solved using get_extra_context).

推荐答案

我建议你删除你的 object_list 视图,

I suggest you remove your object_list view,

为这个特定的视图定义一个字典,

define a dictionary for this specific view,

   all_models_dict = {
        "template_name": "contacts/index.html",
        "queryset": Individual.objects.all(),
        "extra_context" : {"role_list" : Role.objects.all(),
                           "venue_list": Venue.objects.all(),
                           #and so on for all the desired models...
                           }
    }

然后在您的网址中:

#add this import to the top
from django.views.generic import list_detail

(r'^$', list_detail.object_list, all_models_dict),

这篇关于Django 将多个模型传递给一个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 08:32