在Django中,要获取在搜索值中找到的列名,可以使用以下方法:
from django.apps import apps
def search_columns(query, model_name):
model = apps.get_model(app_label='your_app_label', model_name=model_name)
fields = model._meta.fields
matching_columns = []
for field in fields:
try:
value = getattr(model.objects.first(), field.name)
if query in str(value):
matching_columns.append(field.name)
except:
pass
return matching_columns
from django.db.models import Q
from your_app.models import YourModel
def search_columns(query, field_names):
q_objects = Q()
for field_name in field_names:
q_objects |= Q(**{field_name + '__contains': query})
matching_rows = YourModel.objects.filter(q_objects)
matching_columns = matching_rows[0]._meta.fields
return [column.name for column in matching_columns]
以上方法均可根据搜索值找到包含该值的列名。关于 Django 的更多信息,可以参考腾讯云官方提供的 Django 文档:Django 文档。
领取专属 10元无门槛券
手把手带您无忧上云