python – Django在多个模型中搜索字段
发布时间:2020-12-20 12:03:49 所属栏目:Python 来源:网络整理
导读:我想在许多模型中搜索多个字段.我不想使用其他应用程序,如’Haystack’,只有纯Django.例如: # models.pyclass Person(models.Model): first_name = models.CharField("First name",max_length=255) last_name = models.CharField("Last name",max_length=25
我想在许多模型中搜索多个字段.我不想使用其他应用程序,如’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’时,我应该得到一个: >人物模型的“Tonny Montana” 解决方法
一种解决方案是查询所有模型
# 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的模型列表,您可以手动执行,或使用类似 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |