【问题标题】:Save search query result into a model with django使用 django 将搜索查询结果保存到模型中
【发布时间】:2019-03-01 03:22:07
【问题描述】:

我认为有以下代码。我想将查询结果(如果为真)保存到另一个模型中。如何做到这一点?

def scan(request):
    print(request.session)
    if request.method == 'POST':
        srch = request.POST['srh']

        if srch:
            match = ReportModel.objects.filter(Q(serialNumber__iexact=srch))
            if match:
                return render(request, 'admin/scan.html', {'sr': match})
            else:
                messages.error(request, 'No result yet for the requested device!')
        else:
            return redirect('/scan/')

    return render(request, 'admin/scan.html')

【问题讨论】:

  • another model 是如何声明的?
  • 与被查询模型相同的字段
  • 我有 2 个相同字段的模型,一个用于丢失,另一个用于找到。所以我想将搜索查询的结果(如果为真)保存到找到的模型。

标签: python django search model updatemodel


【解决方案1】:

有一种方法。您可以创建自己的缓存。

逻辑是这些步骤:

  1. 假设有AB 模型。
  2. B 模型中将search_result 字段定义为None
  3. 当您通过A 模型进行查询(搜索)时,只需检查B.search_result 值,如果是None,则将search_result 值更改为查询结果(确保您的查询已执行)并返回。如果不是None返回值(B.search_result)。
  4. 当您的模型 A 发生操作(插入、删除、更新)时,将 B.search_result 更改为无。

这是简单的缓存数据。而当你在queryset中使用all()filter(**kwargs)方法时,它不会执行查询,所以将其包装到列表中或将其转储到json中,而不是更改B.search_result的值。

【讨论】:

  • 谢谢,但请注意,我的搜索结果返回了与过滤条件相关联的所有字段。在这种情况下,应将所有字段定义为无?
  • 不,你应该只做B.search_result = None,当你搜索结果为真时,你只做B.search_result = {'field_of_a_1': value1,'field_of_a_2': value2, ...}就够了。
  • 这不是一个好的答案。该问题询问如何将查询保存到模型中。这与缓存完全不同 - docs.djangoproject.com/en/3.2/topics/cache.
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 2016-05-30
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多