根据我上次的更新,解决此问题的最佳方法似乎是通过扩展程序中的 IPackageController 并使用 before_search() 修改搜索参数。
但是,这很好用,如果 CKAN 允许在其主要搜索页面(数据集和组织 ?fq=num_resources:[1 TO *] 并附加到 fq)上传递额外的 fq 过滤器,那就太好了。此外,似乎数据集在将参数分配给fq 方面与组织略有不同。您可以从他们的操作中的这两行中看到这一点(dataset search vs organization read)。就我而言,我决定只为数据集搜索处理这个。
主要作品
# In plugin class implement IPackageController.
class CustomPlugin(plugins.SingletonPlugin, toolkit.DefaultDatasetForm):
...
plugins.implements(plugins.IPackageController)
# Lower in plugin class add needed functions from IPackageController,
# I decided to add them all and leave them untouched to avoid various
# errors I was getting.
def before_search(self, search_params):
u'''Extensions will receive a dictionary with the query parameters,
and should return a modified (or not) version of it.
Basically go over all search_params and look for values that contain my
additional filter and remove the double quotes. All fq values are a
single string, so do exact match to not remove other escaping / quotes.
In query string in URL if you do `?num_resources=0` you get datasets with no
resources (the opposite of this query string).
'''
for (param, value) in search_params.items():
if param == 'fq' and 'num_resources:"[' in value:
v = value.replace('num_resources:"[1 TO *]"', 'num_resources:[1 TO *]')
search_params[param] = v
return search_params
def after_search(self, search_results, search_params):
return search_results
def before_index(self, pkg_dict):
return pkg_dict
def before_view(self, pkg_dict):
return pkg_dict
def read(self, entity):
return entity
def create(self, entity):
return entity
def edit(self, entity):
return entity
def delete(self, entity):
return entity
def after_create(self, context, pkg_dict):
return pkg_dict
def after_update(self, context, pkg_dict):
return pkg_dict
def after_delete(self, context, pkg_dict):
return pkg_dict
def after_show(self, context, pkg_dict):
return pkg_dict
然后对于 UI,我在 search.html 模板上添加了一个自定义方面列表。
<div>
<section class="module module-narrow module-shallow">
{% block facet_list_heading %}
<h2 class="module-heading">
<i class="fa fa-filter"></i>
{% set title = 'Resources (data)' %}
{{ title }}
</h2>
{% endblock %}
{% block facet_list_items %}
{% set title = 'Has Resources (data)' %}
<nav>
<ul class="{{ nav_class or 'list-unstyled nav nav-simple nav-facet' }}">
{% set href = h.remove_url_param('num_resources',
extras=extras,
alternative_url=alternative_url)
if c.fields_grouped['num_resources']
else h.add_url_param(new_params={'num_resources': '[1 TO *]' },
alternative_url=alternative_url) %}
<li class="{{ nav_item_class or 'nav-item' }}{% if c.fields_grouped['num_resources'] %} active{% endif %}">
<a href="{{ href }}" title="{{ title }}">
<span>{{ title }}</span>
</a>
</li>
</ul>
</nav>
{% endblock %}
</section>
</div>
这样做不会使用 IFacets 添加新构面,因为这会为 num_resources 添加一个构面列表,该列表提供 0、1、2、3、...(或任何对您的设置有意义的选项)例如,如果一个数据集有 15 个资源,则将其显示为一个选项)。
我还对search_form.html sn-p 进行了一些修改,以使构面过滤器显示我想要的方式,但这只是额外的。