Django search fields in multiple models

前端 未结 1 1326
情话喂你
情话喂你 2021-01-30 15:22

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(model         


        
相关标签:
1条回答
  • 2021-01-30 15:28

    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)
    

    Then combine the results, if you want

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题