I want to update field:number
with 'current number + random number' :
Here is my code, I have 650 games in database,and it needs almost 8 seconds to update it.
objs = Game.objects.all()
for obj in objs:
Game.objects.filter(name=obj.name).update(number=F('number') + random.randint(1,100))
If I use F function, the the code below will have a problem :
the random.randint(1,100)
is the same for all rows ,
Can I randomly use different numbers with F funciton? Or Is there some method by which I can speed up my query ??
Game.objects.all().update(number=F('number') + random.randint(1,100))
答案 0 :(得分:1)
是的,您可以先在第一步生成随机数,然后将它们分配给Game模型的数字字段, 像这样:
objs = Game.objects.all()
for obj in objs:
random_number = random.randint(1,100)
obj.number = random_number
obj.save()
或者以更好的方式,你不需要遍历for循环,只需使用它:
def generate_random(request):
number = random.randint(1,100)
return number
def your_view(request):
objs = Game.objects.all()
objs.update(number=F('number') + generate_random() )
感谢。