小编典典

如何将 Django QuerySet 转换为列表?

all

我有以下内容:

answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()])

然后稍后:

for i in range(len(answers)):
    # iterate through all existing QuestionAnswer objects
    for existing_question_answer in existing_question_answers:
        # if an answer is already associated, remove it from the
        # list of answers to save
        if answers[i].id == existing_question_answer.answer.id:
            answers.remove(answers[i])           # doesn't work
            existing_question_answers.remove(existing_question_answer)

我收到一个错误:

'QuerySet' object has no attribute 'remove'

我已经尝试了各种将 QuerySet 转换为标准集或列表的方法。没有任何效果。

如何从 QuerySet 中删除一个项目,这样它就不会从数据库中删除它,并且不会返回一个新的 QuerySet(因为它处于一个不起作用的循环中)?


阅读 107

收藏
2022-07-16

共1个答案

小编典典

你可以这样做:

import itertools

ids = set(existing_answer.answer.id for existing_answer in existing_question_answers)
answers = itertools.ifilter(lambda x: x.id not in ids, answers)

在评估 QuerySet
阅读并注意将整个结果加载到内存中是不好的(例如 via list())。

参考:itertools.ifilter

*关于评论的 *更新:

有多种方法可以做到这一点。一种(就内存和时间而言可能不是最好的一种)是完全相同的:

answer_ids = set(answer.id for answer in answers)
existing_question_answers = filter(lambda x: x.answer.id not in answers_id, existing_question_answers)
2022-07-16