- 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/
让我们写一个简单的类在我的脑海中解释: class SomeClass { var happyToUsed = 10 } 并创建一个对象 let someObject = SomeClass(
采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别? 例如 impl SomeStruct { fn example1(self) { } fn ex
请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 se
backbone.js 开始于: //Establish the root object, `window` (`self`) in the browser, or `global` on the s
做的事: self = self.init; return self; 在 Objective-C 中具有相同的效果: self.init() 快速? 例如,在这种情况下: else if([form
我查看了关于堆栈溢出的一些关于使用[weak self]和[unowned self]的问题的评论。我需要确保我理解正确。 我正在使用最新的 Xcode - Xcode 13.4,最新的 macOS
我面临在以下模型类代码中的 self.init 调用或分配给 self 之前使用 self 的错误tableview单元格项目,它发生在我尝试获取表格单元格项目的文档ID之后。 应该做什么?请推荐。
晚上好。 我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。 有一个示例函数。 func exampleFunction() { functionWithEsca
我需要在内心深处保持坚强的自我。 我知道声明[weak self]就够了外封闭仅一次。 但是guard let self = self else { return }呢? ,是否也足以为外部闭包声明一
代码 use std::{ fs::self, io::self, }; fn rmdir(path: impl AsRef) -> io::Result { fs::remo
我检查了共享相同主题的问题,但没有一个解决我遇到的这种奇怪行为: 说我有一个简单的老学校struct : struct Person { var name: String var age:
我应该解释为什么我的问题不是重复的:TypeError: can only concatenate list (not “str”) to list ...所以它不是重复的,因为该帖子处理代码中出现的
我有一个 trait,它接受一个类型参数,我想说实现这个 trait 的对象也会符合这个类型参数(使用泛型,为了 Java 的兼容性) 以下代码: trait HandleOwner[SELF
这个问题在这里已经有了答案: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 个答案) 关闭 8
我总是找到一些类似的代码newPromise.promiseDispatch.apply(newPromise, message),我不明白为什么不使用newPromise.promiseDispat
我看到类似的模式 def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... 非
mysql查询示例: SELECT a1.* FROM agreement a1 LEFT JOIN agreement a2 on a1.agreementType = a2.agreementTy
self.delegate = self; 这样做有什么问题吗?正确的做法是什么? 谢谢,尼尔。 代码: (UITextField*)initWith:(id)sender:(float)X:(flo
为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。
这个问题已经有答案了: What does the ampersand (&) before `self` mean in Rust? (1 个回答) 已关闭去年。 我不清楚 self 之间有什么区别
我是一名优秀的程序员,十分优秀!