2012-09-20 123 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.

相关问题