Django 新手 - 使用多字段表单,如何消除查询集中的空字段

发布于 2024-08-21 11:06:36 字数 837 浏览 3 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七颜 2024-08-28 11:06:36

您可以编写:

if form.is_valid():
    opts = {}
    for key in form.cleaned_data:
        if form.cleaned_data[key] != '':
            opts[key] = form.cleaned_data[key]
    artwork = Inventory.objects.filter(**opts)
    return object_list(request, queryset=artwork)

如果过滤器参数与表单字段具有相同的名称。

You could write:

if form.is_valid():
    opts = {}
    for key in form.cleaned_data:
        if form.cleaned_data[key] != '':
            opts[key] = form.cleaned_data[key]
    artwork = Inventory.objects.filter(**opts)
    return object_list(request, queryset=artwork)

If filter parameters have the same names as form fields.

近箐 2024-08-28 11:06:36

我发现简单的事情是创建一个字典,例如:

query_dict = { 'marketingname' : art_name , 'marketingnumber'=art_number}

然后利用 python 的 kwargs 语法很好地传递它,即

Inventory.objects.filter(**query_dict)

要构建初始字典,如果你的 clean_data 键对应于你传递给 过滤器()

query_dict = dict([ (k,v) for k,v in form.cleaned_data.items() if v ])

但这里的情况似乎并非如此(markettingname!= artname)

Something simple I find is to create a dictionary like:

query_dict = { 'marketingname' : art_name , 'marketingnumber'=art_number}

Then exploiting python's kwargs syntax to pass it in nicely, i.e.

Inventory.objects.filter(**query_dict)

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().

query_dict = dict([ (k,v) for k,v in form.cleaned_data.items() if v ])

But that doesn't seem to be the case here (markettingname != artname)

幸福不弃 2024-08-28 11:06:36

你可以尝试这样做:

if art_name != '' and art_number != '':  
    artwork = Inventory.objects.filter(marketingname = art_name, marketingnumber = art_number)

如果你使用 try 会更好

try:
    artwork = Inventory.objects.filter(marketingname = art_name, marketingnumber = art_number)
except:
    # do some error handling

you could try doing:

if art_name != '' and art_number != '':  
    artwork = Inventory.objects.filter(marketingname = art_name, marketingnumber = art_number)

even better if you use try

try:
    artwork = Inventory.objects.filter(marketingname = art_name, marketingnumber = art_number)
except:
    # do some error handling
帝王念 2024-08-28 11:06:36

这应该有效:

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))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文