Django 新手 - 使用多字段表单,如何消除查询集中的空字段
我是 Django 新手,所以如果这是一个愚蠢的问题,请原谅我。我有一个搜索表单,上面有多个字段。我只想通过提交的非空字段来过滤我的查询集。我该怎么做?我知道您可以将查询集和 Q 对象链接在一起,但我不知道如何从链中消除空键/值对。我知道以下内容不起作用,但我认为它可能会帮助您深入了解我正在寻找的内容。谢谢。
def art_search(request):
if request.method == 'GET':
form = AdvSearch(request.GET)
if form.is_valid():
art_name = form.cleaned_data['art_name']
art_number = form.cleaned_data['art_number']
artwork = Inventory.objects.filter(
if art_name is not u'':
Q(marketingname=art_name),
if art_number is not u'':
Q(marketingnumber=art_number)
)
return object_list(request, queryset=artwork)
else:
form = AdvSearch()
return render_to_response('art/search.html', {
'form': form,
})
I'm a Django newbie, so please forgive me if this is a stupid question. I have a search form that has multiple fields on it. I only wish to filter my queryset by those fields submitted that aren't empty. How do I do that? I'm aware you can chain querysets and Q objects together, but I don't know how to eliminate empty key/value pairs from the chain. I know the following doesn't work, but I thought it might provide insight into what I'm looking for. Thank you.
def art_search(request):
if request.method == 'GET':
form = AdvSearch(request.GET)
if form.is_valid():
art_name = form.cleaned_data['art_name']
art_number = form.cleaned_data['art_number']
artwork = Inventory.objects.filter(
if art_name is not u'':
Q(marketingname=art_name),
if art_number is not u'':
Q(marketingnumber=art_number)
)
return object_list(request, queryset=artwork)
else:
form = AdvSearch()
return render_to_response('art/search.html', {
'form': form,
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以编写:
如果过滤器参数与表单字段具有相同的名称。
You could write:
If filter parameters have the same names as form fields.
我发现简单的事情是创建一个字典,例如:
然后利用 python 的 kwargs 语法很好地传递它,即
要构建初始字典,如果你的 clean_data 键对应于你传递给
过滤器()
。但这里的情况似乎并非如此(markettingname!= artname)
Something simple I find is to create a dictionary like:
Then exploiting python's kwargs syntax to pass it in nicely, i.e.
To build the initial dictionary you can use a list comprehension if your cleaned_data keys correspond to the parameters you're passing off to
filter()
.But that doesn't seem to be the case here (markettingname != artname)
你可以尝试这样做:
如果你使用 try 会更好
you could try doing:
even better if you use try
这应该有效:
Inventory.objects.filter(Q(marketingname=art_name) | Q(marketingnumber=art_number))
this should work:
Inventory.objects.filter(Q(marketingname=art_name) | Q(marketingnumber=art_number))