我一直在尋找適當的解決方案。但找不到任何必須拿出我自己的。 views.py
class VocationsListView(ListView):
context_object_name = "vocations"
template_name = "vocations/vocations.html"
paginate_by = 10
def get_queryset(self):
get = self.request.GET.copy()
if(len(get)):
get.pop('page')
self.baseurl = urlencode(get)
model = Vocation
self.form = SearchForm(self.request.GET)
filters = model.get_queryset(self.request.GET)
if len(filters):
model = model.objects.filter(filters)
else:
model = model.objects.all()
return model
def get_context_data(self, **kwargs):
context = super(VocationsListView, self).get_context_data(**kwargs)
context['form'] = self.form
context['baseurl']= self.baseurl
return context
models.py
class Vocation(models.Model):
title = models.CharField(max_length = 255)
intro = models.TextField()
description = models.TextField(blank = True)
date_created = models.DateTimeField(auto_now_add = True)
date_modified = models.DateTimeField(auto_now = True)
created_by = models.ForeignKey(User, related_name = "vocation_created")
modified_by = models.ForeignKey(User, related_name = "vocation_modified")
class Meta:
db_table = "vocation"
@property
def slug(self):
return defaultfilters.slugify(self.title)
def __unicode__(self):
return self.title
@staticmethod
def get_queryset(params):
date_created = params.get('date_created')
keyword = params.get('keyword')
qset = Q(pk__gt = 0)
if keyword:
qset &= Q(title__icontains = keyword)
if date_created:
qset &= Q(date_created__gte = date_created)
return qset
所以基本上我這一段代碼添加到每個模型類,在這裏我想實現搜索功能。這是因爲對於每一個模型過濾器必須被明確地準備
@staticmethod
def get_queryset(params):
date_created = params.get('date_created')
keyword = params.get('keyword')
qset = Q(pk__gt = 0)
if keyword:
qset &= Q(title__icontains = keyword)
if date_created
qset &= Q(date_created__gte = date_created)
return qset
它準備,我用它來從模型
完美!我不得不交換繼承順序tho(ListView,FormMixin)以保持分頁工作。 – laffuste
這是很好,但我應該在模板中使用輸出所有窗體。我只看到第一個元素的一個表單實例和作爲模型列表的objects_list。 –
你能列出模板代碼嗎? –