djangodjango-modelsdjango-shell

Django Shell update objects value


I want to increase the prices by 30% in django shell.

models.py:

price = models.FloatField(null=True)

shell:

from product.models import Product
Product.objects.all().update(price=price*1.3)

error:

NameError: name 'price' is not defined

Solution

  • You need to use an F expression to reference the field in the database https://docs.djangoproject.com/en/3.2/ref/models/expressions/#f-expressions

    from django.db.models import F
    from product.models import Product
    Product.objects.all().update(price=F('price')*1.3)