如何将每个搜索词存储到 Django 中的数据库中

Ami*_*oui 4 python django

我的网站上有一个搜索表单。当用户键入查询(如 iPhone)时,程序会将该关键字存储到名为“SearchTerms”的数据库中,其中包含搜索该关键字的人数。

例子:

search_term: iPhone

search_count: 50

这意味着有 50 人在我的网站上搜索了“iPhone”这个词。我希望在搜索词存在时更新搜索词,如果不存在则添加搜索词。

这是我尝试做的:

模型.py

class SearchTerms(models.Model):
  search_terms = models.CharField(max_length=255, blank=True, null=True)
  total_searches = models.IntegerField(default=0)
  updated_on = models.DateTimeField(auto_now_add=True)

  search_objects = SearchTermManager()

  class Meta:
    verbose_name_plural = "Search Terms"

  def __str__(self):
    return self.search_terms
Run Code Online (Sandbox Code Playgroud)

视图.py

class SearchView(ListView):
    template_name = 'search.html'
    paginate_by = 20
    count = 0

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['count'] = self.count or 0
        context['query'] = self.request.GET.get('q')
        return context

    def get_queryset(self):
        request = self.request
        query = request.GET.get('q', None)

        if query is not None:
            product_results = Product.objects.search(query)

            # combine querysets
            queryset_chain = chain(
                    product_results
            )        
            qs = sorted(queryset_chain, 
                        key=lambda instance: instance.pk, 
                        reverse=True)
            self.count = len(qs) # since qs is actually a list
            return qs
        return Product.objects.none() # just an empty queryset as default
Run Code Online (Sandbox Code Playgroud)

还有一件事,我正在处理 2 张桌子。所以当我在搜索表单中输入“iPhone”时:

  1. 术语 iPhone 将添加到“SearchTerms”表中(如果已经存在,则增加值)。
  2. 在“产品”表中搜索该术语并显示结果。

我不知道如何同时处理 2 个表。

rud*_*dra 5

您可以尝试这样使用get_or_create

class SearchView(ListView):
    template_name = 'search.html'
    paginate_by = 20
    count = 0
    queryset = Product.objects.none()

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['count'] = context.get('object_list').count()
        context['query'] = self.request.GET.get('q')
        return context

    def update_search_query(self, query):
      term, _ = SearchTerms.objects.get_or_create(
           defaults={'search_terms':query}, 
           search_terms__iexact=query
      )
      term.total_searches += 1
      term.save()

    def get_queryset(self):
        request = self.request
        query = request.GET.get('q', None)
        if query:
           self.update_search_query(query)
           return Product.objects.search(query).order_by('-pk')
        return super().get_queryset()
Run Code Online (Sandbox Code Playgroud)

在这里,我减少了一些基于链接和排序的代码,您可能不需要它,因为您可以使用order_by. 然后我还添加了一个用于获取计数的代码。在上下文中,您将从 key 获取查询集object_list,我正在使用count方法来获取结果的数量。