gpt4 book ai didi

python - 获取切片后 Django 无法更新查询

转载 作者:行者123 更新时间:2023-12-01 05:37:51 25 4
gpt4 key购买 nike

我有一个疑问...

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

我不想再进行一次数据库调用来检索对象,而且我已经将它们存储在内存中了,这有什么意义。

所以我尝试像这样更新:

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

但我收到以下错误消息:

一旦获取切片就无法更新查询。

为什么?这附近有吗?我想更新内存中已有的对象,而不是再次调用来检索它们。

这是我的完整代码,必须解决这个问题......

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)

最佳答案

使用 django 数据库事务以获得最佳性能:

https://docs.djangoproject.com/en/1.5/topics/db/transactions/

例如:

from django.db import transaction

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)

with transaction.commit_on_success():
for m in message_batch:
m.update(send_date=datetime.datetime.now(), billed=True)

这将换行,例如。如果不在事务中执行更新,则一次调用数据库即可更新 5000 行,而不是调用数据库 5000 次。

关于python - 获取切片后 Django 无法更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18467945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com