python - 如何在迭代时从 Queryset 中删除一个项目?

标签 python django django-queryset

我有以下内容:

jobs = Task.objects.filter(created__month=month, created__year=year)

for job in jobs:
    try:
        _ = User.all_objects.filter(user=job.creator_id, customer=job.customer_id).reverse()[0]
    except IndexError:
        # Remove this job
        job.delete()  # This is deleting object from the Database which I don't want to happen. 
        # I'm looking for a method such as jobs.remove(job)

从上面看,我不知道是否可以在我的第一个查询中使用“exclude”。这就是为什么我想知道是否有办法从 Queryset 中删除“工作”。

最佳答案

QuerySet 的主要吸引力在于它是惰性的,但无论如何您都在评估所有内容,所以我认为如果您只是将它制成一个带有列表理解。

jobs = [j for j in jobs if  User.all_objects.filter(user=job.creator_id, customer=job.customer_id)]

关于python - 如何在迭代时从 Queryset 中删除一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889664/

相关文章:

python - 如何计算两个 pandas.Timestamp 系列之间的差异(以纳秒为单位)

python - 使用 pip 安装包的最新兼容版本

python - Django:SQL 防注入(inject)管理器.py

django - 避免对查询模型加上所有外键关联进行 n+1 次查询?

Django ORM : Conditional filtering

python - 当 .where() 无法将数据转换回原始类型时该怎么办

python - 从 python 脚本调用 mongoimport

python - 如何在 django(python)的元组中删除多余的 ','

python - Django ORM orderby exact/prominent match 排在最前面

python - 如何将大字典的对象以特定比例分配给较小的字典?