【问题标题】:Issue sending keys, values to django Q()向 django Q() 发送键、值
【发布时间】:2021-09-23 16:29:24
【问题描述】:

我正在尝试使用 django 查询过滤一些 ID 并尝试有效地执行此操作,我希望获得与我之前创建的效率较低的函数相同的结果,但我遇到了字典键使用的问题问

from tmd import models
from django.db.models import Q

category = {
    "utility": models.Account.UTILITY, 
    "system": models.Account.SYSTEM
    }
country = {
    "United States": models.Country.objects.get(name='USA'),
    "Canada": models.Country.objects.get(name='CA'),
}


def get_a(stage=None, **kwargs):
        base_args =[]
        base_args.append(Q(stage__in=stage))
        for key, value in kwargs.items():
            base_args.append(Q(key= value))
                    
        a_ids = models.Account.objects.filter(*base_args).values_list('id', flat=True)
        print("Number of a_ids: {}".format(a_ids.count()))
        return a_ids

输入:

a_ids = get_a(country=country["USA"], category=category["utility"])

问题正好在这一行:

base_args.append(Q(key= value))

如果我可以输入为每次迭代更改键,这将得到解决

【问题讨论】:

    标签: python python-3.x django


    【解决方案1】:

    你想要

    base_args.append( Q( **{ key: value} ))
    

    我想知道你是否需要 Q。处理动态 kwargs 的相同方式可以让你做到

    a_ids = models.Account.objects.filter( stage__in=stage
               )                  .filter( **kwargs 
               )
    

    这是各种关键字=值过滤条件的逻辑

    【讨论】:

    • 谢谢您,效果非常好。你能给我一个 **kwargs 的例子来输入你的第二个答案吗?
    • 如果我正确地遵循了您的代码,那就是您的!否则,如果 kwargs{'a':5, 'baz':'foo'},则 .filter( **kwargs).filter( a=5, baz='foo') 相同(使用和逻辑,过滤对象同时使用 a=5 和 baz='foo'。)
    猜你喜欢
    • 2020-12-08
    • 2016-03-31
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多