2012-09-20 112 views
8

我有2個表productscatagories通過外鍵連接。 我需要使用領域catagories.price_markup如下更新場products.new_costDjango更新表使用來自另一個表的數據

UPDATE products p 
INNER JOIN categories c ON p.category_id = c.id 
SET p.new_cost = ROUND(p.pleer_cost * (1 + c.price_markup/100), -1) 
WHERE p.update = 1 

在SQL它很容易,但如何使用Django ORM辦呢?

我的簡化的嘗試不起作用Cannot resolve keyword 'category.price_markup' into field.

Product.actived.select_related('category').filter(update=1)).update(new_cost=F('pleer_cost') * F('category.price_markup')) 

回答

-5

Django使用__(雙下劃線)相關領域。將category.price_markup更改爲category__price_markup,您應該清楚。

+5

錯誤:'此查詢中不允許加入字段引用'。有關它的票據https://code.djangoproject.com/ticket/14104 – Deadly

+2

在這種情況下,請嘗試在過濾器和更新之間使用額外的內容,然後在更新中使用額外的字段。類似於Product.activated.select_related('category')。filter(update = 1).extra(select = {'_ new_price':'pleer_cost * category.price_markup'})。update(new_price = _new_price)'。您可能需要稍微調整一下,但這是一般想法。 –

+0

試過了亞歷克斯,仍然不會工作它會抱怨說「_new_price」不在現場列表中。 更新功能不關心你選擇了哪些字段,它只檢查你建模的字段有 – Ramast

-1
from django.db import transaction 

with transaction.atomic(): 
    for p in Product.objects.select_related('category').filter(update=1) 
     p.new_cost= p.pleer_cost * p.category.price_markup 
     p.save() 
-1

AFAIU它可以與

for row in ModelName.objects.filter(old_field__isnull=False): 
    row.new_field = row.old_field.subfield 
    row.save() 
+0

對於大表格非常慢 – shadi

8

被workarounded按照documentation,使用join子句更新不支持,請參閱:

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')) 

此外,根據本issue,這是由設計,並沒有計劃在不久的將來改變它:

The actual issue here appears to be that joined F() clauses aren't permitted in update() statements. This is by design; support for joins in update() clauses was explicitly removed due to inherent complications in supporting them in the general case.

相關問題