## 12.5 模式5:可重用的搜索混合(Mixin)视图
在这个例子中,我们将要覆盖到如何在对应两个不同模型的两个视图中重用一个搜索表单。
假设两个模型都有一个title字段(此模式也会证明为什么在项目中使用命名标准是一个好的事情)。这个例子将会证明,在Flavor和IceCreamStore模型中,一个单一的CBV也能用来提供简单的搜索功能。
我们通过在我们的视图中创建一个简单的搜索Mixin开始:
EXMAPLE 12.13# core/views.pyclass TitleSearchMixin(object):def get_queryset(self):# Fetch the queryset from the parent's get_querysetqueryset = super(TitleSearchMixin, self).get_queryset()# Get the q GET parameterq = self.request.GET.get("q")if q:# return a filtered querysetreturn queryset.filter(title__icontains=q)# No q is specified so we return querysetreturn queryset
上面代码你应该十分熟悉,因为我们几乎一字不差的使用在Forms + View例子中。下面是如何在Flavor和IceCreamStore视图中使用,首先是Flavor视图:
EXAMPLE 12.14# add to flavors/views.pyfrom django.views.generic import ListViewfrom core.views import TitleSearchMixinfrom .models import Flavorclass FlavorListView(TitleSearchMixin, ListView):model = Flavor
添加到冰淇淋商店视图:
EXAMPLE 12.15# add to stores/views.pyfrom django.views.generic import ListViewfrom core.views import TitleSearchMixinfrom .models import Storeclass IceCreamStoreListView(TitleSearchMixin, ListView):model = Store
至于表单?我们仅仅对每个ListView在HTML定义:
EXAMPLE 12.16{# form to go into stores/store_list.html template #}<form action="" method="GET"><input type="text" name="q" /><button type="submit">search</button></form>
和
EXAMPLE 12.17{# form to go into flavors/flavor_list.html template #}<form action="" method="GET"><input type="text" name="q" /><button type="submit">search</button></form>
现在我们在两个视图中有了相同的Mixin。Mixins是一个很好的方式来重用代码,但是在单一的类中使用太多Mixin将会导致难以维护代码。像一如既往那样,尽可能保证你的代码简单明了。
