首页 > 解决方案 > 蟒蛇 | 如何在具有相同类的模板中显示 2 个模型信息

问题描述

我需要在模板中获取 2 个模型信息。因为有些站点有设备。(我需要在设备列表中显示站点详细信息)如何在模板中显示 2 个模型信息?

class StationDetailView(DetailView):
    model = Station
    model = Device
    template_name = "station/detail_station.html"

在此处输入图像描述

谢谢!

标签: djangodjango-modelsdjango-views

解决方案


查看此链接,了解如何从 django 文档 https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/#adding-向详细视图类添加额外的上下文(模型)语境外

class StationDetailView(DetailView):
    model = Station
   
    template_name = "station/detail_station.html"

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the Device
        context['device_list'] = Device.objects.all()
        return context

推荐阅读