[英]Django Custom Queryset Using Listview if Parameters Exist in URL
I have a listview for my blog:我的博客有一个列表视图:
#views.py
class BlogListView(ListView):
model = Blog
template_name = 'blog/index.html'
context_object_name = 'blogs'
ordering = ['-date_posted']
paginate_by = 5
#urls.py
path('', BlogListView.as_view(), name='blog-index'),
In my model I have different type of blogs, such as video blog or text blog.在我的模型中,我有不同类型的博客,例如视频博客或文本博客。 my model is like this:我的模型是这样的:
class Blog(models.Model):
TYPE = (
('Video', 'Video'),
('Text', 'Text'),
)
type = models.CharField(max_length=10, choices=TYPE, default='Text')
Now I want to use request.GET.get('type')
to query different types.现在我想使用request.GET.get('type')
来查询不同的类型。 For example if I go to the url, 127.0.0.1:8000/?type=video
I want only blog that are the type video to show.例如,如果我转到 url 127.0.0.1:8000/?type=video
我只想显示视频类型的博客。 Is it possible to do this with only this listview, or do I have to create others.是否可以仅使用此列表视图来执行此操作,还是必须创建其他视图。 I need help with making of this feature.我需要帮助制作此功能。
Yes , you can implement this in the ListView
by overriding the .get_queryset(…)
method [Django-doc] :是的,您可以通过覆盖.get_queryset(…)
方法 [Django-doc]在ListView
实现此功能:
class BlogListView(ListView):
model = Blog
template_name = 'blog/index.html'
context_object_name = 'blogs'
ordering = ['-date_posted']
paginate_by = 5
def get_queryset(self):
type = self.request.GET.get('type')
qs = super().get_queryset()
if type is not None:
return qs.filter(type__iexact=type)
return qs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.