本文介绍了多个模型通用 ListView 到模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在通用 IndexView 中列出 2 个模型的最简单方法是什么?我的两个模型是 CharacterSeries
和 CharacterUniverse
.
What is the SIMPLEST method for getting 2 models to be listed in a generic IndexView? My two models are CharacterSeries
and CharacterUniverse
.
我的views.py
from .models import CharacterSeries, CharacterUniverse
class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_series_list'
def get_queryset(self):
return CharacterSeries.objects.order_by('name')
class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_universe_list'
def get_queryset(self):
return CharacterUniverse.objects.order_by('name')
我需要知道最短最优雅的代码.看了很多,但不想使用mixin.我可能没有被指出正确的方向.
I need to know the shortest and most elegant code. Looked a lot but don't want to use mixins. I am perhaps not being pointed in the right direction.
谢谢大家.
推荐答案
您可以像这样将一个查询集作为上下文传递到 ListView 中,
You can pass the one queryset in as context on the ListView like this,
class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_series_list'
model = CharacterSeries
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'character_universe_list': CharacterUniverse.objects.order_by('name'),
'more_context': Model.objects.all(),
})
return context
def get_queryset(self):
return CharacterSeries.objects.order_by('name')
这篇关于多个模型通用 ListView 到模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!