在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 關(guān)于update的一點問題

關(guān)于update的一點問題

class A(models.Model):
    name = models.CharField(max_length=10)
    b = models.ForeignKey('B')
    
class B(models.Model):
    name = models.CharField(max_length=10)  

我想把A的name字段批量更新成B的name,嘗試著寫了下面的代碼

A.objects.all().update(name=F('B__name')) 

FieldError: Joined field references are not permitted in this query 會報這個錯誤,google了一下發(fā)現(xiàn)F函數(shù)是不支持這樣做的, stackoverflow上僅有的幾個回答也是推薦使用sql語句來做。
想問問大家有什么別的好方法實現(xiàn)么?

回答
編輯回答
眼雜

謝邀,這個情況文檔有談到了:

However, unlike F() objects in filter and exclude clauses, you can’t introduce joins when you use F() objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an F() object, a FieldError will be raised:

# This will raise a FieldError
>>> Entry.objects.update(headline=F('blog__name'))

詳情:https://docs.djangoproject.co...

所以我覺得要么用sql語句,要么用循環(huán)逐一設(shè)置:

for item in A.objects.all():
    item.name = item.b.name
    item.save()
2017年2月7日 18:39