38👍
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)
)
19👍
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.
- [Django]-Embedding a Plotly chart in a Django template
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
- [Django]-How can I MODIFY django to create "view" permission?
0👍
rows = Product.objects.filter(old_field__isnull=False)
for row in rows:
row.new_field = row.old_field.subfield
Product.objects.bulk_update(rows, ['new_field'])
- [Django]-Django CSRF Cookie Not Set
- [Django]-Django vs. Model View Controller
- [Django]-Django: Best way to merge migrations conflicts