Django一旦切片被取消,就无法更新查询 [英] Django Cannot update a query once a slice has been taken

查看:600
本文介绍了Django一旦切片被取消,就无法更新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询...

message_batch = Message.objects.all()[500]

我不想再进行另一个数据库调用来检索对象,除了我已经在内存中有什么要点。

I don't want to have to make another database call to retrieve the objects, besides I already have them in memory so whats the point.

所以我试图像这样更新:

So I tried to update like this:

message_batch.update(send_date=datetime.datetime.now(), status="Sent")

但是我收到以下错误消息:

But I get the following error message:

一旦切片被取消,就无法更新查询。

Cannot update a query once a slice has been taken.

为什么?周围有周围吗?我想要更新我已经在内存中的对象,不会再打个电话来检索它们。

Why? Is there a around around this? I want to update the objects I already have in memory not make another call to retrieve them.

这是我的完整代码,必须围绕着这个....

This is my full code, has to be way around this....

total = Message.objects.filter(status="Unsent", sender=user,   batch=batch).exclude(recipient_number__exact='').count()

for i in xrange(0,total,500):
    message_batch = Message.objects.filter(status="Unsent").exclude(recipient_number__exact='')[i:i+500]
    # do some stuff here
    # once all done update the objects
    message_batch.update(send_date=datetime.datetime.now(), billed=True)


推荐答案

您可以通过主键更新对象:

You can update objects by their primary keys:

base_qs = Message.objects.filter(status="Unsent", sender=user, batch=batch).exclude(recipient_number__exact='')
total = base_qs.count()

for i in xrange(0, total, 500):
    page = list(base_qs[i:i+500])
    page_ids = [o.pk for o in page]
    # Do some stuff here
    base_qs.filter(pk__in=page_ids).update(send_date=datetime.datetime.now(), billed=True)

这篇关于Django一旦切片被取消,就无法更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆