本文介绍了如何将 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 转换为标准集或列表的方法.没有任何效果.

I've tried all sorts to convert the QuerySet to a standard set or list. Nothing works.

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

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)?

推荐答案

你可以这样做:

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

更新评论:

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

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 转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 05:42