当您需要为模型的不同属性单独获取结果时,优化查询集调用

时间:2018-03-29 10:52:45

标签: django django-queryset

我有一个可以拥有多个属性的模型帐户。

基于属性执行其他查询。要获取属性,我会进行查询:

def get_context_data(self, **kwargs):

    accounts_h = Account.objects.filter(is_home=True)
    accounts_i = Account.objects.filter(is_featured=True)
    accounts_t = Account.objects.filter(is_t=True)

    products_h = Product.objects.filter(account_id__in=accounts_h)
    products_i = Product.objects.filter(account_id__in=accounts_i)
    companies_t = Company.objects.filter(account_id__in=accounts_t)

问题是我必须对帐户上的多个属性(超过6个)以及其他非最佳的相关模型进行类似的查询。

如何优化?

2 个答案:

答案 0 :(得分:1)

我们可以优化下面的数据库查询。我已将3个Account的查询替换为1个和2个Product的查询为1。

当我们向数据库查询时,它必须将数据提取到易失性存储器中并为每个查询处理它。我做的是我立刻从db获取所有结果并进行处理。它节省了db

中数据的获取时间
from django.db.models import Q

def get_context_data(self, **kwargs):

    accounts = Account.objects.filter(Q(is_home=True)| Q(is_featured=True)| Q(is_t=True))
    accounts_h = []
    accounts_i = []
    accounts_t = []
    for acc in accounts:
        if acc.is_home:
          accounts_h.append(acc.id)
        if acc.is_t:
          accounts_t.append(acc.id)
        if acc.is_i:
          accounts_i.append(acc.id)
    products = Product.objects.filter(account_id__in=accounts)
    products_h = filter(lambda obj : obj.id n accounts_h, products)
    products_i = filter(lambda obj : obj.id n accounts_i, products)
    companies_t = Company.objects.filter(account_id__in=accounts_t)

答案 1 :(得分:0)

也许这就是你想要的:

def get_context_data(self, **kwargs):
    products_h = Product.objects.filter(account__is_home=True)
    products_i = Product.objects.filter(account__is_featured=True)
    companies_t = Company.objects.filter(account__is_t=True)