Django使用另一个表中的数据更新表 [英] Django update table using data from another table

查看:629
本文介绍了Django使用另一个表中的数据更新表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个通过外键连接的表产品类别
我需要使用字段 catagories.price_markup 更新字段 products.new_cost ,如下所示:

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

在SQL中是如此简单,但是如何使用Django ORM做到呢?

In SQL it's so easy, but how to do it using Django ORM?

我的简化尝试不起作用不能将关键字 category.price_markup解析为字段。

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


推荐答案

您不能使用F,但是可以使用Subquery和OuterRef:

You cannot use F, but you can use Subquery and OuterRef:

from django.db.models import Subquery, OuterRef

cost = Category.objects.filter(
    id=OuterRef('category_id')
).values_list(
    'price_markup'
)[:1]

Product.objects.update(
    new_cost=Subquery(cost)
)

这篇关于Django使用另一个表中的数据更新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆