我有以下几点:
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)
当QuerySets被求值时读取,并注意将整个结果加载到内存中是不好的(例如通过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)
你可以这样做:
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)
当QuerySets被求值时读取,并注意将整个结果加载到内存中是不好的(例如通过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)