python Django for循环中有很多类似的查询

cgvd09ve  于 2023-04-28  发布在  Python
关注(0)|答案(1)|浏览(96)

我在我的get_queryset函数中有for循环,我正在将请求中的信息解析到我的django模板中,但由于某种原因,我试图通过GUID进行过滤,我得到了21个类似的sql查询
我试图在for循环之前获取CleanSections,但这没有帮助
有什么建议吗?
views.py

def get_queryset(self):
    session = requests_cache.CachedSession('budget_cache', backend=backend, stale_if_error=True,
                                           expire_after=360)
    url = config('API') + 'BUDGET'
    response = session.get(url, auth=UNICA_AUTH)

    response_json = None

    queryset = []

    if response_json is None:
        print('JSON IS EMPTY')
        return queryset
    else:
        all_sections = CleanSections.objects.all()

        for item in response_json:
            my_js = json.dumps(item)

            parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js)

            if parsed_json.ObjectGUID == select_front:
                obj = parsed_json.ObjectGUID
            else:
                continue

            for budget in parsed_json.BudgetData:
                budget.SectionGUID = all_sections.filter(GUID=budget.SectionGUID)
                budget.СompletedContract = budget.СompletedContract * 100
                budget.СompletedEstimate = budget.СompletedEstimate * 100
                queryset.append(budget)
    return queryset
6yjfywim

6yjfywim1#

我找到了一个解决的方法:我们实际上可以使用GUID = key和Section的值名称的字典

queryset = []
dict_of_sections= {}

all_sections = CleanSections.objects.all()

for i in all_sections:
    dict_of_sections[i.GUID] = i.name

budget.SectionGUID = dict_of_sections[UUID(budget.SectionGUID)]

相关问题