我试图弄清楚如何将get_queryset与我的Django detailview合并。在正常的用例中,我可以正常工作,将get_queryset添加到DetailView中,瞧!可以。...但是这个用例有些不同。
我正在使用FormView来获取搜索值,然后成功后,我将返回detailview。这也正常工作。当我尝试合并get_queryset来覆盖queryset时,事情就出现了问题。
这是我的代码:
FormView
didFinishLaunchingWithOptions
然后在我的author_search.html中:
UIApplication.shared.statusBarStyle = .lightContent
当用户在搜索中输入一个值时...会返回一个DetailView屏幕:
class AuthorSearchView(LoginRequiredMixin,FormView):
form_class = AuthorSearchForm
template_name = 'author_search.html'
def get_form_kwargs(self):
kwargs = super(AuthorSearchView, self).get_form_kwargs()
kwargs['user'] = self.request.user
kwargs['q'] = self.request.GET.get("q")
return kwargs
上面的代码工作正常。注意:我没有在操作参考中使用PK参考,因为这种方法不需要它。对于上面的代码,我的网址是:
<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail' %}">
但是,当我尝试将get_queryset而不是get_object与以下代码合并时:
class AuthorSearchDetailView(LoginRequiredMixin,DetailView):
model = Author
context_object_name = 'author_detail'
template_name = 'author_search_detail.html'
def get_object(self, queryset=None):
return get_object_or_404(Author, request_number=self.request.GET.get("q"))
return get_object_or_404
然后我得到:
url(r'^author_search_detail/$',views.AuthorSearchDetailView.as_view(), name='author_search_detail'),
我得到这个是因为我正在使用DetailView而不在我的URL中提供PK。
但是,当我在HTML和URL中添加一个pk时,如下所示:
def get_queryset(self):
queryset = super(AuthorSearchDetailView, self).get_queryset()
return queryset.filter(request_number=self.request.GET.get("q"))
URL:
AuthorSearchDetailView must be called with either an object pk or a slug in the URLconf.
我明白了...
<form method="GET" autocomplete=off action="{% url 'Author:author_search_detail'pk=author.pk %}">
奇怪的是,如果我用pk = user.pk替换pk = author.pk,我不会得到错误。所以这使我相信,因为我最初使用FormView来获取DetailView success_url ... FormView中的pk引用存在问题。它不了解PK。
答案 0 :(得分:0)
因此,在对这个问题进行了过多的思考之后,结果发现我对它的想法太过思索了……
我只需要将我的get_object更新为已过滤的条件...
const data = client.db([dbname]).collection([collectionname]).find([searchcriteria]).toArray()
将用户和ID添加到get_object的过滤条件中。