如何将数据从视图传递到Django中的自定义mixin?

时间:2018-06-14 00:57:52

标签: django

我的两个观点共享大量代码,这使得难以维护。出于这个原因,我决定将公共代码移动到自定义mixin中。

一个简单的例子:

class StatisticsMixin(object):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_products = Product.objects.filter(user=self.request.user).select_related()

        context["total_products"] = user_products.count()
        context["total_products_open"] = user_products.total_new()

        return context

现在,我的观点看起来像这样:

class DashboardView(LoginRequiredMixin, StatisticsMixin, TemplateView):
    model = Product
    template_name = "products/dashboard.html"

     def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_products = Product.objects.filter(user=self.request.user).select_related()

        # Some other code

        return context

class AnalyticsView(LoginRequiredMixin, StatisticsMixin, TemplateView):
    model = Product
    template_name = "products/analytics.html"

     def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_products = Product.objects.filter(user=self.request.user).select_related()

        # Some other code

        return context

自定义mixin中的问题如下:StatisticsMixin:

user_products = Product.objects.filter(user=self.request.user).select_related()

在不同的视图中可能是别的。

所以,我正在尝试为自定义mixin找到一种方法,从视图中获取数据,而不是硬编码。

1 个答案:

答案 0 :(得分:1)

class StatisticsMixin(object):
    def get_user_products(self):
        return Product.objects.filter(user=self.request.user).select_related()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_products = self.get_user_products()

        context["total_products"] = user_products.count()
        context["total_products_open"] = user_products.total_new()

        return context

class DashboardView(LoginRequiredMixin, StatisticsMixin, TemplateView):
    model = Product
    template_name = "products/dashboard.html"

     def get_user_products(self):
        return what ever you want