【问题标题】:django ListView specifying variable available for all methods inside the classdjango ListView 指定变量可用于类内的所有方法
【发布时间】: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


    【解决方案1】:

    将其保存在 self.shop 中。

    get_queryset 是第一个调用的方法(参见the code for BaseListView's get method)。因此,一种解决方案是将变量放在那里,就像在代码中一样,然后将其保存到 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()
    

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

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

    【讨论】:

    • 成功了,谢谢。对于任何通用视图(创建、删除),我都需要相同的功能,因为大部分功能取决于 /shop/shop_name/ url 变量。基视图类是否有通用方法,或者我应该检查每个视图中调用的“第一个”方法(例如 UpdateView 中的 get_object() 吗?)
    • 我认为最简单的解决方案是为所有视图覆盖 get_queryset 或 get_object。有一个通用的 View 类,所有基于类的视图都派生自(请参阅code.djangoproject.com/browser/django/trunk/django/views/…),从技术上讲,您可以将其放在那里,但是您将拥有自己的 View 类,并且默认的 CBV 不会从它继承,所以我认为你最终会编写更多代码。
    • 这个答案违背了这个编程原则:stackoverflow.com/questions/19284857/… 更不用说如果 Django 开发人员更改调用方法的顺序,它可能不再起作用。
    • this 回答之后,我将作业放入get() 中。将变量保存为 self.* 是一个很好的建议 - 谢谢!
    猜你喜欢
    • 2013-07-27
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多