Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django-如何使用kwargs实现这一点_Python_Django_Keyword Argument - Fatal编程技术网

Python django-如何使用kwargs实现这一点

Python django-如何使用kwargs实现这一点,python,django,keyword-argument,Python,Django,Keyword Argument,我想知道在执行查询时何时触摸数据库。更准确地说,何时执行查询: 我有这个kwargs dic: kwargs = {'name__startswith':'somename','color__iexact':'somecolor'} 但仅对于name\uu startswithquery,我需要distinct()。不适用于颜色\uuuuiExact 我想,我会在循环中设置name\uu启动distinct(),如下所示: for q in kwargs: if q == 'name__

我想知道在执行查询时何时触摸数据库。更准确地说,何时执行查询:

我有这个kwargs dic:

kwargs = {'name__startswith':'somename','color__iexact':'somecolor'}
但仅对于
name\uu startswith
query,我需要
distinct()
。不适用于
颜色\uuuuiExact

我想,我会在循环中设置
name\uu启动
distinct()
,如下所示:

for q in kwargs: 
  if q == 'name__startswith':
    Thing.objects.filter(name__startswith=somename).distinct('id')
然后动态查询所有:

allthings = Thing.objects.filter(**kwargs)
但这是错误的,我似乎在做两件不同的事情

如何动态执行这两个查询

django查询集是,因此实际查询不是

在实际使用数据之前,不应在上面执行任何查询。这对于过滤您希望执行的查询非常有用


从:

QuerySet是惰性的–创建QuerySet的行为不涉及任何数据库活动。您可以整天将过滤器堆叠在一起,Django在计算QuerySet之前不会实际运行查询。看看这个例子:

>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)
虽然这看起来像是三次数据库命中,但实际上它只在最后一行(print(q))命中数据库一次。通常,查询集的结果只有在您“请求”查询后才能从数据库中获取。执行此操作时,将通过访问数据库来评估查询集。有关何时进行求值的详细信息,请参阅何时对查询集求值。

您可以使用它在django中创建动态查询

query = models.Q(name__startswith=somename)

query &= models.Q('color__iexact':'somecolor')

all_things = Thing.objects.filter(query).distinct('name')
也读

但是您也为
color\uuuuuiExact
设置了
distinct
,我还需要
name\uuuuuu startswith
否,distinct采用列名,您只需提供想要设置distinct的列即可。更新了我的答案,按名称进行区分哦,好的,太好了。非常感谢你。我对
Q
一无所知。你给了我新的方法。感谢Tons,为了更明确一点,它不会在
颜色上执行distinct
,如果您想要颜色和名称的不同组合,您可以执行
distinct('name','color')
谢谢,我决定在所有查询上执行
distinct
,这不会损害任何东西。无论如何感谢您的帮助使用
distinct
可以显著降低查询速度:
query = models.Q(name__startswith=somename)

query &= models.Q('color__iexact':'somecolor')

all_things = Thing.objects.filter(query).distinct('name')