【发布时间】:2011-09-03 21:06:54
【问题描述】:
我的网址有一个关键字“shop_name”变量。 还有带有“名称”字段的 Shop 模型。
在我的 ListView 类中,我需要对 Shop 模型进行重复查询,以从 Shop.get_type() 方法中获取 unicode 变量。根据结果,选择适当的模板目录或查询集(使用子类 django 模型)。
这是代码。
class OfferList(ListView):
def get_template_names(self):
shop = Shop.objects.get(name=self.kwargs['shop_name'])
return ["shop/%s/offer_list" % shop.get_type()]
def get_queryset(self):
shop = Shop.objects.get(name=self.kwargs['shop_name'])
Offer = shop.get_offers_model()
return Offer.objects.all()
def get_context_data(self, **kwargs):
# again getting shop instance here ...
shop = Shop.objects.get(name=self.kwargs['shop_name'])
context = super(OfferList, self).get_context_data(**kwargs)
context['shop'] = shop
return context
问题是什么是最好的方法,所以我可以获得一些适用于所有方法的 var(在这种情况下为商店)?我不是 python 大师(可能是基本问题)。我已经尝试使用 init 覆盖,但我无法获得 exchange_name(在 urls.py 中指定)来获得正确的“商店”实例。我想避免重复。
谢谢
【问题讨论】:
标签: python django generics listview views