【问题标题】:Django - Reduce URL query-string lengthDjango - 减少 URL 查询字符串长度
【发布时间】:2017-05-18 12:02:37
【问题描述】:

我使用 Django Forms 已经有一段时间了,但最近我不得不创建一个表单来使用 MultipleChoiceField 搜索数据。 由于 URL 必须在用户之间共享,因此表单对服务器执行 GET 以将搜索参数保留在查询字符串中。 问题是如果选中多个选项,URL 的长度会增加太多。例如:

http://www.mywebsite.com/search?source=1&source=2&source=3...

是否有使用 django 表单来获取如下网址:

http://www.mywebsite.com/search?source=1-2-3...

或者创建压缩查询字符串参数的令牌是否是更好的方法?

然后使用该表单在 ElasticSearch 上进行搜索。我没有使用 djangos 模型。

谢谢!

【问题讨论】:

  • 我的回答有帮助吗?

标签: django http django-forms query-string


【解决方案1】:

TemplateView 上覆盖getget_context_data 可以工作。然后你可以有一个这样的 URL:http://www.mywebsite.com/search?sources=1,2

class ItemListView(TemplateView):
    template_name = 'search.html'

    def get(self, request, *args, **kwargs):
        sources = self.request.GET.get('sources')
        self.sources = sources.split(',') if sources else None

        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        if self.sources:
            context['search-results'] = self.get_search_results(
                self.sources,
            )

        return context

    def get_search_results(self, sources):
        """
        Retrieve items that have `sources`.
        """
        # ElasticSearch code here…

        data = {
            '1': 'Honen',
            '2': 'Oreth',
            '3': 'Vosty',
        }

        return [data[source_id] for source_id in sources]

现在,如果请求/search?sources=1,2 URL,模板上下文中将包含HonenOreth 作为变量search-results

【讨论】:

  • 嗨,马特,我认为这是个好主意,但不适用于我的问题。我忘了提到我没有使用 Django 模型。数据来自 ElasticSearch,因此不涉及传统模型。我会更新问题。
  • 在这种情况下,您可以使用 TemplateView 并添加一个从 ElasticSearch 检索结果的方法。我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
相关资源
最近更新 更多