[英]When to use get, get_queryset, get_context_data in Django?
[英]Django: get_queryset after get_context_data
我正在過濾我的項目 model 對象,由經過身份驗證的用戶使用我的 ListView 中的 get_context_data
class myprojects(LoginRequiredMixin, ListView):
model = Project
template_name = 'my_project_list.html'
ordering = ['project_title']
def get_context_data(self, *args, **kwargs):
context = super(myprojects, self).get_context_data(**kwargs)
context['my_projects'] = Project.objects.filter(engineer=self.request.user)
return context
在模板中
{% for my_project in my_projects %}
{{ my_project }}
{% endfor %}
我的模板中有一個表單來搜索項目,我在同一個 ListView 上使用了 get_queryset。 我收到了搜索,但它沒有在模板中過濾
class myprojects(LoginRequiredMixin, ListView):
model = Project
template_name = 'my_project_list.html'
ordering = ['project_title']
def get_context_data(self, *args, **kwargs):
context = super(myprojects, self).get_context_data(**kwargs)
context['my_projects'] = Project.objects.filter(engineer=self.request.user)
return context
def get_queryset(self, *args, **kwargs):
context = super().get_queryset(*args, **kwargs)
search = self.request.GET.get('buscar', None)
print(search)
if search:
context = context.filter(
Q(project_title__icontains=search) |
Q(category__title__icontains=search)
).distinct()
return context
注意:當我使用{% for project in object_list %}
而不是{% for project in my_projects %}
時,它搜索沒有問題,但我不再有用戶過濾器
只需在 get_queryset 方法中過濾
def get_queryset(self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwargs)
search = self.request.GET.get('buscar', None)
queryset = queryset.filter(engineer=self.request.user)
if search:
queryset = queryset.filter(
Q(project_title__icontains=search) |
Q(category__title__icontains=search)
).distinct()
return queryset
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.