web-dev-qa-db-ja.com

Django複数のモデルの検索フィールド

多くのモデルで複数のフィールドを検索したい。 「Haystack」のような純粋なDjangoだけのような他のアプリを使いたくありません。例えば:

# 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」と入力すると、次のようになります。

  • Personモデルの「Tonny Montana」
  • Restaurantモデルの「Tonny's Restaurant」
  • pizzaモデルの「Tonny's Special Pizza」。
10
Konrados

1つの解決策は、すべてのモデルをクエリすることです

# 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)

わかりました、これはより一般的な解決策です。すべてのモデルのすべてのCharFieldsを検索します。

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)

これにより、すべてのクエリセットのリストが表示されます。次に、操作するために選択した形式に成形できます。

埋めるモデルのリストを取得するにはsearch_models、手動で行うか、または get_models 。動作の詳細については、ドキュメントをご覧ください。

15
NS0