从查询集结果创建生成器 - Python?

时间:2018-03-10 06:17:36

标签: django generator django-queryset python-3.6

我是python的新手我需要将以下函数转换为生成器以节省内存,我该如何实现?

question = <QuerySet [<Question: foobar?.>]>
for index, question in enumerate(questions):
        if question["pk"] == self.pk:
            try:
                next_question = questions[index + 1]
                if next_question["pk"]:
                    prev_next.update({"next" : next_question["pk"] })
            except IndexError:
                prev_next.update({"complete" : True })

            try:
                if index > 0:
                    previous_question = questions[index - 1]
                    if previous_question["pk"]:
                        prev_next.update({"prev" : previous_question["pk"] })
            except IndexError:
                pass

    return prev_next

0 个答案:

没有答案