django ListView 指定可用于类内所有方法的变量

Rob*_*ert 5 python generics django listview view

我的网址有一个关键字“shop_name”变量。还有带有“名称”字段的商店模型。

在我的 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
Run Code Online (Sandbox Code Playgroud)

问题是最好的方法是什么,这样我可以获得一些可用于所有方法的 var (在本例中为商店)?我不是 python 专家(可能是基本问题)。我尝试过init覆盖,但后来我无法获取 Exchange_name (在 urls.py 中指定)来获取正确的“shop”实例。我想避免重复。

谢谢

Ofr*_*viv 4

将其保存在 self.shop 中。

get_queryset 是第一个调用的方法(请参阅BaseListView 的 get 方法的代码)。因此,一种解决方案是将变量放在那里,就像在代码中所做的那样,然后将其保存到 self.shop (就像 BaseListView 对 self.object_list 所做的那样)。

def get_queryset(self):
    self.shop = Shop.objects.get(name=self.kwargs['shop_name'])
    Offer = self.shop.get_offers_model()
    return Offer.objects.all()
Run Code Online (Sandbox Code Playgroud)

然后在其他方法中,您可以使用 self.shop:

def get_template_names(self):        
    return ["shop/%s/offer_list" % self.shop.get_type()]
Run Code Online (Sandbox Code Playgroud)