Python 如何在django中将筛选器添加到值来自URL的queryset中?
views.pyPython 如何在django中将筛选器添加到值来自URL的queryset中?,python,django,Python,Django,views.py class ListPosts(generic.ListView): template_name = 'posts/list_posts.html' context_object_name = 'list_posts' def get_queryset(self): #kwargs={ "slug": user.slug } qs = Post.objects.all().filter(user=self.request
class ListPosts(generic.ListView):
template_name = 'posts/list_posts.html'
context_object_name = 'list_posts'
def get_queryset(self):
#kwargs={ "slug": user.slug }
qs = Post.objects.all().filter(user=self.request.user)
return qs
def get_queryset(self):
qs = Posts.objects.all().filter(user__slug__exact=self.kwargs['slug'])
return qs
这里添加了过滤器,因此queryset只过滤登录用户的帖子。
我的问题是如何在URL中显示来自slug的用户值的帖子
url.py
url(r'^(?P<slug>[\w.@+-]+)/Posts/$', ListPosts.as_view(), name='user_posts'),
url(r'^(?P[\w.@+-]+)/Posts/$,ListPosts.as_view(),name='user_Posts'),
示例:username/posts
我知道可以通过从URL传递kwargs来完成。但是如何在同一视图中使用两个不同的模型呢?如果我理解正确,您希望使用URL中的slug值进行过滤。您可以使用self.kwargs字典访问它。可以这样做:
class ListPosts(generic.ListView):
template_name = 'posts/list_posts.html'
context_object_name = 'list_posts'
def get_queryset(self):
qs = Post.objects.filter(
user=self.request.user,
some_field=self.kwargs['slug'])
return qs
views.py
class ListPosts(generic.ListView):
template_name = 'posts/list_posts.html'
context_object_name = 'list_posts'
def get_queryset(self):
#kwargs={ "slug": user.slug }
qs = Post.objects.all().filter(user=self.request.user)
return qs
def get_queryset(self):
qs = Posts.objects.all().filter(user__slug__exact=self.kwargs['slug'])
return qs
我发现Django:invalid literal for int(),以10为基数“>解决了这个问题
Quote.objects.filter([model]\uuuuu[field]\uuuu exact=[which])
检查request.GET()
。我发现这个错误无法将关键字“slug”解析为fieldqs=Post.objects.all().filter(user=self.request.user,slug=self.kwargs['slug'))