可用于类内部的所有方法的Django的ListView指定变量 [英] django ListView specifying variable available for all methods inside the class

查看:452
本文介绍了可用于类内部的所有方法的Django的ListView指定变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网址有一个关键字shop_name变量。
还有以名称字段中店模式。

My url has a keyword "shop_name" variable. There's also the Shop model with "name" field.

在我的ListView类我需要重复查询中心模型从Shop.get_type()方法得到一个单向code变量中。根据结果​​,一个合适的模板目录中选择,或查询集(使用子类Django模型)。

In my ListView class I need to make repeating queries to Shop model to get a unicode variable from Shop.get_type() method. Depending on the result, a proper template directory is selected or queryset (Using subclassed django models).

这里的code。

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

问题是什么是最好的方式,这样我就可以得到一些变种(店在这种情况下)适用于所有的方法呢?我不是一个Python的用户(可能是基本的问题)。我试着的init 覆盖但我无法得到EXCHANGE_NAME(在urls.py指定)得到正确的店的实例。我想避免重复。

Question is what is the best way, so I can get some var (shop in this case) available for all methods ? I'm not a python guru (may be the basic problem). I've tried with init overriding but then I couldn't get exchange_name (specified in urls.py) to get the right "shop" instance. I would like to avoid repeating.

感谢

推荐答案

在self.shop保存它。

Save it in self.shop.

get_queryset被调用(见的的code为BaseListView的get方法)。所以,一个解决办法是让您的变量存在,就如同你在code做的,然后也保存到self.shop(就像BaseListView确实与self.object_list)。

get_queryset is the first method called (see the code for BaseListView's get method). So one solution would be to get your variable there, just as you do in your code, and then also save it to self.shop (just as the BaseListView does with 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()

然后在你的其他的方法可以使用​​self.shop:

Then in your other methods you can use self.shop:

def get_template_names(self):        
    return ["shop/%s/offer_list" % self.shop.get_type()]

这篇关于可用于类内部的所有方法的Django的ListView指定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆