生成 A-Z,指向同一个 ClassBasedView 的链接并进行搜索
Generating A-Z, links that go to the same ClassBasedView and do a search
我有一个 A-Z(字母)列表,当用户点击其中任何一个时,我需要进行搜索。
知道了,怎么查询:
Post.objects.filter(name__istartswith='A')
因为我只想使用一个 CBV,所以我需要一种方法:
1) 在 Django 模板中生成 urls 模式 -> (string.string.ascii_uppercase)
2) 如何从 url 模式
中获取字母
您可以使用视图 class 的 self.kwargs
属性获取字母(参见相关 part of doc)。假设你的模式是这样的:
url(r'^(?P<letter>[a-z])/$', SomeView.as_view(), name='detail'),
在 SomeView
class 中你可以覆盖 get_queryset
方法:
class SomeView(ListView):
model = Post
template_name = 'users/user_post_list.html'
def get_queryset(self):
return Post.objects.filter(name__istartswith=self.kwargs['letter'])
我有一个 A-Z(字母)列表,当用户点击其中任何一个时,我需要进行搜索。
知道了,怎么查询:
Post.objects.filter(name__istartswith='A')
因为我只想使用一个 CBV,所以我需要一种方法:
1) 在 Django 模板中生成 urls 模式 -> (string.string.ascii_uppercase) 2) 如何从 url 模式
中获取字母您可以使用视图 class 的 self.kwargs
属性获取字母(参见相关 part of doc)。假设你的模式是这样的:
url(r'^(?P<letter>[a-z])/$', SomeView.as_view(), name='detail'),
在 SomeView
class 中你可以覆盖 get_queryset
方法:
class SomeView(ListView):
model = Post
template_name = 'users/user_post_list.html'
def get_queryset(self):
return Post.objects.filter(name__istartswith=self.kwargs['letter'])