I have 2 tables products
and catagories
connected by foreign key.
I need to update field products.new_cost
using field catagories.price_markup
as following:
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
In SQL it's so easy, but how to do it using Django ORM?
My simplified try doesn't work 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'))
Note: My answer is outdated now, Django 1.11 introduced
OuterRef
which implements this feature. Check Andrey Berenda answer below.According to the documentation, updates using join clauses are not supported, see:
Also, according to this issue, this is by design and there is no plans to change it in the near future:
Django uses
__
(double underscore) for related fields. Change thatcategory.price_markup
to acategory__price_markup
and you should be in the clear.You cannot use F, but you can use Subquery and OuterRef:
AFAIU it can be workarounded with