如何将Django QuerySet转换为列表

我有以下内容:

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(因为它处于循环状态,因此无法使用)?

回答:

你可以这样做:

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时阅读,请注意,将整个结果加载到内存中(例如通过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)

以上是 如何将Django QuerySet转换为列表 的全部内容, 来源链接: utcz.com/qa/434661.html

回到顶部