如何将Django QuerySet转换为列表 [英] How to convert a Django QuerySet to a list
问题描述
我有以下内容:
answers = Answer.objects.filter(id__in = [answer.id for answer in
answer_set.answers.all()])
然后稍后:
for i in range(len(answers)):
#遍历所有现有的QuestionAnswer对象
for existing_question_answers中的existing_question_answer:
#如果一个答案已经相关联,从
#的答案列表中删除它,以保存
如果答案[i] .id == existing_question_answer.answer.id:
答案。删除(answer [i])#不工作
existing_question_answers.remove(existing_question_answer)
我收到一个错误:
'QuerySet'对象没有属性'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不在ids,答案)
阅读 时,djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluatedrel =noreferrer> 并注意到它不是很好地将整个结果加载到内存中(例如通过 list()
)。
更新关于评论:
有很多种方法可以做到这一点。一个(这可能不是最好的记忆和时间)是完全一样的:
answer_ids = set (answer.id回答答案)
existing_question_answers =过滤器(lambda x:x.answer.id不在answers_id,existing_question_answers)
I have the following:
answers = Answer.objects.filter(id__in=[answer.id for answer in
answer_set.answers.all()])
then later:
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)
I get an error:
'QuerySet' object has no attribute 'remove'
I've tried all sorts to convert the QuerySet to a standard set or list. Nothing works.
How can I remove an item from the QuerySet so it doesn't delete it from the database, and doesn't return a new QuerySet (since it's in a loop that won't work)?
You could do this:
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)
Read when QuerySets are evaluated and note that it is not good to load the whole result into memory (e.g. via list()
).
Reference: itertools.ifilter
Update with regard to the comment:
There are various ways to do this. One (which is probably not the best one in terms of memory and time) is to do exactly the same :
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转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!