我想在1个算法中添加所有列以进行搜索。如果可能的话。
这样的事情:
*更新* (我已更新views.py和search_table.html) 它只是正确搜索url字段。我在这些字段中输入的id和标题将为我提供整个表格。
views.py
def search_table(request,pk): table_name = Crawledtables.objects.get(id = pk) t = create_model(table_name.name)
q = request.GET['q']
if q is not None:
query = t.objects.filter(Q(id__icontains=q) | Q(title__icontains=q) | Q(url__icontains=q))
return render(request, 'search/results_table.html', {'tbl_name': table_name,
'details': query,
'query': q})
else:
return HttpResponse("Please submit a search term!")
results_table.html
<strong> {{ tbl_name }}</strong>
<p> You searched for: <strong>{{ query }}</strong></p>
{% if details %}
<p> Found {{ details|length }}</p>
<div class="row">
<table class="table table-bordered sortable">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Url</th>
</tr>
</thead>
<tbody>
{% for lists in details %}
<tr>
<td>{{ lists.id }}</td>
<td>{{ lists.title }}</td>
<td><a href="{{ lists.url }}" target="_blank">{{ lists.url }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p> No results found</p>
{% endif %}
{% endblock %}
search_table.html
{% if tbl_name %}
<form action="/search/{{ tbl_name.id }}/results" method="GET">
{% endif %}
<input type="text" name="q" placeholder="Id">
<input type="text" name="q" placeholder="Title">
<input type="text" name="q" placeholder="Url">
<input type="submit" value="Search">
</form>
更新
models.py
def create_model(db_table):
class CustomMetaClass(ModelBase):
def __new__(cls, name, bases, attrs):
model = super(CustomMetaClass, cls).__new__(cls, name, bases, attrs)
model._meta.db_table = db_table
return model
class AllTables(models.Model):
__metaclass__ = CustomMetaClass
id = models.IntegerField(primary_key=True)
title = models.CharField(db_column='Title', blank=True, null=True, max_length=250)
url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True,
null=True)
created_at = models.DateTimeField(db_column='Created_at')
return AllTables
答案 0 :(得分:1)
在语法中使用:AND(&amp;)和OR(|)
from django.db.models import Q
t.objects.filter(Q(id__icontains=q_id) | Q(title__icontains=q_title) | Q(url__icontains=q_url))