2014-01-29 21 views
12

所以我想通過運行以下來更新我的模型:Django的˚F表達加盟領域

FooBar.objects.filter(something=True).update(foobar=F('foo__bar')) 

,但我得到了以下錯誤:

FieldError: Joined field references are not permitted in this query 

如果不與F允許表達式...我如何實現此更新?

給出this ticket的信息,我現在明白了,這是不可能的,絕不會在Django來實現,但有什麼辦法來實現這一更新?也許有一些工作?我不想使用循環,因爲有超過1000萬個對象,所以SQL比python快得多。

回答

5

爲什麼不使用原始的SQL這裏: 基於this,它將會像

from django.db import connection 

raw_query = ''' 
update app_foobar set app_foobar.foobar = 
(select app_foo.bar from app_foo where app_foo.id = app_foobar.foo_id) 
where app_foobar.something = 1; 
''' 

from django.db import connection 
cursor = connection.cursor() 
cursor.execute(raw_query) 
+1

這裏的另一種方式做到這一點: 「」「UPDATE app_foobar B設置mycol = foo.othercol FROM app_foo a WHERE a.id = b.foo_id「」「。 –