Answer the question
In order to leave comments, you need to log in
How to bulk change a value in Django (for example, increase the price by % or value)?
So there is a Product model (simplified in the example):
class Product(models.Model):
title = models.CharField(max_length=100, verbose_name="Название изделия", unique=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name="Категория")
price_mp = models.DecimalField(max_digits=9, decimal_places=2, default=0.00)
price_kp = models.DecimalField(max_digits=9, decimal_places=2, default=0.00)
act = 'plus' # или minus, это собственно действие
val = 5 # или 250 по второму заданию
unit = 'percent' # или ruble
target = 'price_category' # или price_all, чтобы знать менять для категории или везде
category = 20 # ну или то, что пришло из формы
type_price = 'all' # или 'mp' или 'kp'
from django.db.models import OuterRef, Subquery # это вверху
...
# хочу выполнить первую вводную, т.е. price_mp в категории
Product.objects.filter(category=20).update(
price_mp = Subquery(
Product.objects.filter(id=OuterRef('id')).annotate( # надо ли мне вообще annotate
'price_mp' + 'price_mp' * val / 100 # в общем я как-то запутался
)
),
# price_kp = 2
)
Answer the question
In order to leave comments, you need to log in
Looks like F-expressions can help you:
https://docs.djangoproject.com/en/2.2/ref/models/e...
Updates the price of all selected products using the current price F('price_mp') to calculate the new price.
Will work with one request, at the database level.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question