多个模型中的Django搜索字段 [英] Django search fields in multiple models

查看:79
本文介绍了多个模型中的Django搜索字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在许多模型中搜索多个字段。我不想只使用纯Django等其他应用,例如 Haystack。例如:

I want to search multiple fields in many models. I don't want to use other apps like 'Haystack' only pure Django. For example:

# models.py

class Person(models.Model):
    first_name = models.CharField("First name", max_length=255)
    last_name = models.CharField("Last name", max_length=255)
    # other fields


class Restaurant(models.Model):
    restaurant_name = models.CharField("Restaurant name", max_length=255)
    # other fields


class Pizza(models.Model):
    pizza_name = models.CharField("Pizza name", max_length=255)
    # other fields

当我输入 Tonny时,我应该得到:

When I type a 'Tonny' I should get a:


  • Tonny Montana 来自 Person 型号

  • 来自 Restaurant 型号的 Tonny's Restaurant

  • pizza 模型的 Tonny's Special Pizza。

  • "Tonny Montana" from Person model
  • "Tonny's Restaurant" from Restaurant model
  • "Tonny's Special Pizza" from pizza model.

推荐答案

一种解决方案是查询所有模型

One solution is to query all the models

# Look up Q objects for combining different fields in a single query
from django.db.models import Q
people = Person.objects.filter(Q(first_name__contains=query) | Q(last_name__contains=query)
restaurants = Restaurant.objects.filter(restaurant_name__contains=query)
pizzas = Pizza.objects.filter(pizza_name__contains=query)

然后根据需要合并结果

from itertools import chain
results = chain(people, restaurants, pizzas)






好的,当然,这是一个更通用的解决方案。搜索所有模型中的所有CharField:


Ok, sure, here's a more generic solution. Search all CharFields in all models:

search_models = [] # Add your models here, in any way you find best.
search_results = []
for model in search_models:
    fields = [x for x in model._meta.fields if isinstance(x, django.db.models.CharField)]
    search_queries = [Q(**{x.name + "__contains" : search_query}) for x in fields]
    q_object = Q()
    for query in search_queries:
        q_object = q_object | query

    results = model.objects.filter(q_object)
    search_results.append(results)

这将为您提供所有查询集的列表,然后您可以将其模制成您选择使用的格式。

This will give you a list of all the querysets, you can then mold it to a format you choose to work with.

要获取填充 search_models 的模型列表,您可以手动执行,也可以使用 get_models 。阅读文档以获取有关其工作原理的更多信息。

To get a list of models to fill search_models, you can do it manually, or use something like get_models. Read the docs for more information on how that works.

这篇关于多个模型中的Django搜索字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆