基于类的通用视图中的冗余

时间:2015-01-26 13:56:19

标签: django django-views django-class-based-views

我有两个简单的基于类的通用视图,它们只是呈现模板。由于它们看起来几乎一样,我想保持干爽,我想问你,现在实现这一目标最聪明,最好的方法是什么:

第一视图

class Foo(TemplateView):
  template_name = "Foo.html"

  def get_context_data(self, **kwargs):
    user = User.objects.get(username = self.request.user)
    context = super(Foo, self).get_context_data(**kwargs)
    context['foo_objs'] = Foo.objects.filter(user = user.id)
    return context

class Bar(TemplateView):
  template_name = "bar.html"

  def get_context_data(self, **kwargs):
    user = User.objects.get(username = self.request.user)
    context = super(Bar, self).get_context_data(**kwargs)
    context['bar_objs'] = Bar.objects.filter(user = user.id)
    return context

1 个答案:

答案 0 :(得分:2)

创建具有附加属性model的中间视图类,然后从中继承您的视图:

class ModelListTemplateView(TemplateView):

    model = None

    def get_template_names(self):
        return [self.model._meta.model_name + '.html']

    def get_context_data(self, **kwargs):
        context = super(ModelListTemplateView, self).get_context_data(**kwargs)
        user = User.objects.get(username=self.request.user)
        context['%s_objs' % self.model._meta.model_name] = \
                                    self.model.objects.filter(user=user.id)
        return context


class FooView(ModelListTemplateView):
    model = Foo

class BarView(ModelListTemplateView):
    model = Bar