django ListView specifying variable available for

2019-05-12 05:37发布

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

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).

Here's the 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

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.

Thanks

1条回答
劫难
2楼-- · 2019-05-12 06:22

Save it in self.shop.

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()

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

def get_template_names(self):        
    return ["shop/%s/offer_list" % self.shop.get_type()]
查看更多
登录 后发表回答