- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Django 2.2.10。我有一个搜索栏,它使用 searchresultsview(listview) 类中的 get_queryset(self) 将搜索结果返回到显示页面。我设置了 paginate_by=10。在前端,我制作了订购表格的链接:`
<th>Title original <a href="?order_by=title_original&direction=asc" class="arrow up"></a> <a href="?order_by=title_original&direction=desc" class="arrow down"></a></th>
在 get_queryset(self) 函数的开头,我有以下代码:
order_by = self.request.GET.get('order_by')
direction = self.request.GET.get('direction')
if order_by is not None and order_by != "" and direction is not None and direction != "":
ordering = Lower(order_by)
if direction == 'desc':
ordering = '-{}'.format(ordering)
publications = Publication.objects.filter(is_deleted=False).order_by(ordering)
'''
paginator = Paginator(publications, 10)
page = self.request.GET.get('page')
try:
all_publications = paginator.page(page)
except PageNotAnInteger:
all_publications = paginator.page(1)
except EmptyPage:
all_publications = paginator.page(paginator.num_pages)
'''
return publications
主要问题是 publications 变量包含所有出版物,我想将其限制为来自先前 get_queryset(self) 调用的出版物。显示页面也是分页的(模板中的 paginate_by = 10)。降序排序不起作用我得到:invalid order_by arguments: ['-Lower(F(title_original))'] 。如果我按升序排序,它在逻辑上不会保留我的搜索结果。我试图找到一个 stackoverflow 解决方案,但解释很少。任何帮助将不胜感激。
使用 django-tables 可能更容易,如果是这样,我愿意接受建议。
查看代码:
class SearchResultsView(ListView):
'''
ListView of the initial search page.
The function get_queryset works for the search bar and the search form home page.
The search bar typically uses q for query otherwise a id for list search.
Use a countries_dict to convert for example Netherlands to NL so that search succeeds.
If a normal field is searched use __icontains if a list element is searched use: __in.
'''
model = Publication
template_name = 'publications/show.html'
context_object_name = 'publications'
publications = Publication.objects.filter(is_deleted=False)
#paginator = Paginator(publications, 10)
#paginator = Paginator(publications, 25)
paginate_by = 10
def get_ordering(self):
order_by = self.request.GET.get('order_by')
direction = self.request.GET.get('direction')
if order_by is not None and order_by != "" and direction is not None and direction != "":
ordering = Lower(order_by)
if direction == 'desc':
ordering = '-{}'.format(ordering)
return ordering
def get_queryset(self):
#form = PublicationForm(self.request.GET)
authors = self.request.GET.getlist('author')
translators = self.request.GET.getlist('translator')
authors = Author.objects.filter(pk__in=authors).all()
translators = Translator.objects.filter(pk__in=translators).all()
form_of_publications = self.request.GET.getlist('form_of_publication')
form_of_publications = FormOfPublication.objects.filter(pk__in=form_of_publications).all()
languages = self.request.GET.getlist('language')
languages = Language.objects.filter(pk__in=languages).all()
affiliated_churches = self.request.GET.getlist('affiliated_church')
affiliated_churches = Church.objects.filter(pk__in=affiliated_churches).all()
content_genres = self.request.GET.getlist('content_genre')
content_genres = Genre.objects.filter(pk__in=content_genres).all()
connected_to_special_occasions = self.request.GET.getlist('connected_to_special_occasion')
connected_to_special_occasions = SpecialOccasion.objects.filter(pk__in=connected_to_special_occasions).all()
currently_owned_by = self.request.GET.getlist('currently_owned_by')
currently_owned_by = Owner.objects.filter(pk__in=currently_owned_by).all()
copyrights = self.request.GET.get('copyrights')
is_a_translation = self.request.GET.get('is_a_translation')
publications = Publication.objects.filter(is_deleted=False)
uploadedfiles = self.request.GET.getlist('uploadedfiles')
uploadedfiles = UploadedFile.objects.filter(pk__in=uploadedfiles).all()
keywords = self.request.GET.getlist('keywords')
keywords = Keyword.objects.filter(pk__in=keywords).all()
translated_from = self.request.GET.getlist('translated_From')
translated_from = Language.objects.filter(pk__in=translated_from).all()
city = self.request.GET.getlist('publication_city')
country = self.request.GET.getlist('publication_country')
collection_country = self.request.GET.getlist('collection_country')
if list(collection_country) != ['']:
collection_country = Country.objects.filter(pk__in=city).all()
if list(country) != ['']:
country = Country.objects.filter(pk__in=city).all()
print('....', city)
if list(city) != ['']:
city = City.objects.filter(pk__in=city).all()
print(publications)
exclude = ['csrfmiddlewaretoken','search']
in_variables = [('author', authors), ('translator', translators), ('form_of_publication', form_of_publications), ('language',languages), ('affiliated_church', affiliated_churches) \
, ('content_genre', content_genres), ('connected_to_special_occasion', connected_to_special_occasions), ('currently_owned_by', currently_owned_by),\
('uploadedfiles', uploadedfiles), ('publication_country', country), ('publication_city', city), ('collection_country', collection_country), ('keywords', keywords), ('translated_from',translated_from)]
special_case = ['copyrights', 'page', 'is_a_translation']
if ('q' in self.request.GET) and self.request.GET['q'].strip():
query_string = self.request.GET['q']
if query_string.lower() in countries_dict.keys():
query_string = countries_dict[query_string.lower()]
search_fields = ['title_original', 'title_subtitle_transcription', 'title_subtitle_European', 'title_translation', 'author__name', 'author__name_original_language', 'author__extra_info', \
'form_of_publication__name', 'editor', 'printed_by', 'published_by', 'publication_date', 'publication_country__name', 'publication_city__name', 'publishing_organisation', 'translator__name', 'translator__name_original_language', 'translator__extra_info', \
'language__name', 'language__direction', 'affiliated_church__name', 'extra_info', 'content_genre__name', 'connected_to_special_occasion__name', 'donor', 'content_description', 'description_of_illustration', \
'nr_of_pages', 'collection_date', 'collection_country__name', 'collection_venue_and_city', 'contact_telephone_number', 'contact_email', 'contact_website', \
'currently_owned_by__name', 'uploadedfiles__description', 'uploadedfiles__uploaded_at', 'general_comments', 'team_comments', 'other_comments', 'keywords__name', 'is_a_translation', 'ISBN_number', 'translated_from__name', 'translated_from__direction']
arabic_query = translator.translate(query_string, dest='ar').text
query_string = to_searchable(query_string)
#arabic_query = to_searchable(arabic_query)
entry_query = get_query(query_string, search_fields)
arabic_query = get_query(arabic_query, search_fields)
print('&&&&&&', query_string)
#publications = publications.filter(entry_query)
publications = publications.filter(Q(entry_query) | Q(arabic_query))
print(publications)
publications = publications.distinct()
return publications
for field_name in self.request.GET:
get_value = self.request.GET.get(field_name)
if get_value != "" and not field_name in exclude and not field_name in [i[0] for i in in_variables] and\
not field_name in special_case:
print('******', field_name)
arabic_query = translator.translate(get_value, dest='ar').text
get_value = to_searchable(get_value)
get_value = get_query(get_value, [field_name])
arabic_query = get_query(arabic_query, [field_name])
print('444444444', get_value)
publications = publications.filter(Q(get_value) | Q(arabic_query))
print('55555555555', publications)
#publications = publications.filter(Q(**{field_name+'__regex':get_value}) | Q(**{field_name+'__icontains':arabic_query}) )
for field_name, list_object in in_variables:
print('****', list_object)
if list_object:
print('------', field_name)
if list(list_object) != ['']:
publications = publications.filter(**{field_name+'__in': list_object})
if str(copyrights) != "unknown" and str(copyrights) != "None":
val = False
if str(copyrights) == "yes":
val = True
print('11111', str(copyrights))
publications = publications.filter(copyrights=val)
print('666666', publications)
if str(is_a_translation) != "unknown" and str(is_a_translation) != "None":
val = False
if str(is_a_translation) == "yes":
val = True
print('11111', str(is_a_translation))
publications = publications.filter(is_a_translation=val)
publications = publications.distinct()
return publications
最佳答案
您可以使用get_ordering
方法
def get_ordering(self):
ordering = self.request.GET.get('ordering', ''#default order param)
return ordering
关于python - Django 从 get_queryset(self) 中排序搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909795/
我收到以下错误: ImproperlyConfigured at /elearning/7447932a-6044-498a-b902-97cbdd0a4001/ DetailView is miss
我通过外键字段进行了一种过滤,具有两个搜索条件:OR 和 AND 以及多项选择。 forms.py class EmployeeSkillFilter(forms.ModelForm): sk
我有一个页面,显示将根据用户选择的月份显示每月收入。 在 HTML 中,有一个包含所有可能的输入。现在在我的 I'm returning a new variable for use in the t
这两段代码乍一看是相同的: class IndexView(generic.ListView): template_name = 'polls/index.html' context_
我最近了解到,当您特别想要执行默认 View 以外的操作时,您应该重写 get 方法: class ExampleView(generic.ListView): template_name =
因为 get_queryset() 只返回一个查询集,我需要查询集 search_store 的长度到模板文件。因此,我尝试通过 get_context_data 将值发送到模板。 我知道我可以通过
我有内置的 Django API,我有返回所有对象的端点。我希望用户为我提供关键字来过滤这个查询集。最好的方法是什么。以及如何做到这一点? 它在 get_queryset 中吗?如果是,你能帮我吗!?
我的代码是 class Leads(LoginRequiredMixin, ListView): def get_queryset(self): q = self.request.GET.get('q
我正在使用 Django 细节 View 。最初,我使用了 URL 模式 url(r'^todo/details/(?P[\d]+)', views.todoDetailView.as_view(),
模型.py: from django.contrib.auth.models import User class Location(models.Model): user = models.F
我更改了 .all 方法,因此它只会选择具有 published=True 的实例: class EventManager(models.Manager): def all(self, *ar
我无法让我的自定义管理器工作... class PublicArtigoManager(models.Manager): def get_queryset(self): ret
我正在使用 Django 2.2.10。我有一个搜索栏,它使用 searchresultsview(listview) 类中的 get_queryset(self) 将搜索结果返回到显示页面。我设置了
我正在尝试关注这个 documentation .我想以某种方式将参数传递给 get_queryset,但不知道如何传递。下面的演示不工作。 class ContextAwareNotificatio
我在 DRF 文档上读到,您可以通过覆盖 .get_queryset() 来过滤查询参数。我正在寻找最佳实践,返回什么,以防过滤器不正确以及在哪里返回错误消息。 我提到的文档是 here我在下面包含源
我有这个 ModelViewset 和一个 ModelSerializer class GenerarFacturaViewset(viewsets.ModelViewSet): serial
我正在使用自定义 mixin 将过滤器应用于使用 MultipleObjectMixin 分页的基于类的 View 的查询集。当我应用过滤器以使当前页面超出数据集范围时,显然会得到 404。我想要做的
我正在覆盖 ModelViewSet 中的 get_queryset 以支持“我”作为过滤器和多个 pk 搜索: class UserViewSet(viewsets.ModelViewSet): q
我正在尝试通过 get_queryset() 函数和使用 order_by() 来编辑 listView 中的顺序当我尝试打印生成的查询时,它会忽略 order_by 查询并仅使用我的模型类中 Met
基本上,我有一个目录 View 集。在 ListView 中,我想进行一些过滤并相应地返回。 相关的目录模型字段是: class Catalog(models.Model): name = m
我是一名优秀的程序员,十分优秀!