gpt4 book ai didi

django - 空查询返回数据库中的所有字段。 Django

转载 作者:行者123 更新时间:2023-12-04 04:13:07 25 4
gpt4 key购买 nike

在搜索表单字段中,如果我不输入任何内容,但按下按钮以搜索查询。查询返回数据库中的每个字段。
Company.objects.exclude(Q(name__isnull=True)).exclude(Q(name__exact=''))
不知何故,对我没有帮助。如果我将它们一起使用或分开使用。
views.py 中的代码是:

class className(listView)
model=Company
template_name='name_of_the_template.html'

def get_queryset(self):
query=self.request.Get.get('q')
query=query.replace('#',' ') //same for ?\/$%^+*()[] *tried to set exclude code here

if query == ' ':
object_list = Company.objects.filter(Q(name__icontains='None'))//sending to the empty object
return object_list
else:
// *tried to set exclude code here
object_list = Company.objects.filter(Q(name__icontains=query))
return object_list

排除代码都没有帮助。我相信我在某处犯了一个简单的错误......因为代码应该可以工作,但不知何故。
我也只是试图摆脱 if else 语句并使用 exclude 语句来查询诸如 ''、' ' 和 null 以及在该过滤器之后进行查询......现在排除对 ' ' 的查询也不起作用......

Django 没有告诉我排除不起作用,所有的工作,除了,它就像不在代码中一样。

最佳答案

如果不输入任何内容,则字符串为空 '' ,或者是 None如果没有传递参数。从而可以检查query的真实性。 ,你最好先.strip()删除任何前导或尾随空格的字符串:

def get_queryset(self):
query = self.request.Get.get('q')
if query is not None:
query = query.replace('#',' ')
query = query.strip()
if not query:
return Company.objects.none()
else:
return Company.objects.filter(name__icontains=query)

在模板中,您可以使用 {% for … %}…{% empty %}…{% endfor %} template block [Django-doc] :
{% for object in object_list %}
{{ object }}
{% empty %}
no objects found!
{% endfor %}

关于django - 空查询返回数据库中的所有字段。 Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com