Django ORM并命中数据库 [英] Django ORM and hitting DB

查看:78
本文介绍了Django ORM并命中数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做类似的事情

I. objects = Model.objects.all()

然后

II. objects.filter(field_1=some_condition)

在第2步中,每次遇到各种情况时,我都会命中db.有什么办法可以使所有数据都先采取行动,然后只照顾结果?

I hit db every time when on the step 2 with various conditions. Is there any way to get all data in first action and then just take care of the result?

推荐答案

在评估q之前,您实际上不会访问数据库,查询是

You actually don't hit the db until you evaluate the qs, queries are lazy.

了解更多信息 .

Read more here.

重新阅读您的问题后,很明显,您在问如何在针对不同条件进行过滤时防止数据库命中.

After re-reading your question it becomes apparent you were asking how to prevent db hits when filtering for different conditions.

qs = SomeModel.objects.all()

qs1 = qs.filter(some_field='some_value')
qs2 = qs.filter(some_field='some_other_value')

通常,您希望数据库为您进行过滤.

Usually you would want the database to do the filtering for you.

您可以通过将qs转换为列表来强制评估qs.这样可以防止进一步的数据库点击,但是这可能比让数据库返回结果更糟糕.

You could force an evaluation of the qs by converting it to a list. This would prevent further db hits, however it would likely be worse than having your db return you results.

qs_l = list(qs)
qs1_l = [element for element in qs_l if element.some_field='some_value']
qs2_l = [element for element in qs_l if element.some_field='some_other_value']

这篇关于Django ORM并命中数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆