Django update table using data from another table

前端 未结 3 1110
庸人自扰
庸人自扰 2020-12-15 05:18

I have 2 tables products and catagories connected by foreign key. I need to update field products.new_cost using field catagorie

3条回答
  •  忘掉有多难
    2020-12-15 05:29

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

提交回复
热议问题