Django update table using data from another table

前端 未结 3 1105
庸人自扰
庸人自扰 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:42

    Note: My answer is outdated now, Django 1.11 introduced OuterRef which implements this feature. Check Andrey Berenda answer.

    According to the documentation, updates using join clauses are not supported, see:

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

    Also, according to this issue, this is by design and there is no plans to change it in the near future:

    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.

提交回复
热议问题