开发者

How to remember objects to be treated after QuerySet.update()

I want to update the bar attribute of a bunc开发者_JAVA百科h of Foo objects using the QuerySet's update() method. Then I want to do something with the modified objects, but I can no more identify them using the bar attribute.

Somehow it doesn't work by remembering the ids.

old_bar = Bar.objects.get(id=1)
new_bar = Bar.objects.get(id=2)

foo_query = Foo.objects.filter(bar=old_bar)
foo_ids = foo_query.values_list('id', flat=True)

print len(foo_ids), foo_query.count(), Foo.objects.filter(id__in=foo_ids).count()
# outputs "42 42 42"

print foo_query.update(bar=new_bar)
# outputs "42"

print len(foo_ids), foo_query.count(), Foo.objects.filter(id__in=foo_ids).count()
# outputs "42 0 0"

Does the update() method modify the ids or what am I doing wrong?


Querysets are lazy, so they are evaluated everytime you use them! Therefore in your example foo_query will be evaluated more than once and return something different depending on the actual objects in your database. foo_ids is therefore not a list of ids, but a ValuesQueryset that evaluates to a list.

Forcing it evaluate to a list should make your example work, as the ids do not change to reflect the actual state of the database: foo_ids = list(foo_query.values_list('id', flat=True)).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜