Search code examples
pythondjangodjango-querysetquery-performance

Django: convert all values of two clumn to absolute value


Lets say, I have a product model with two columns, price, sold. I want to convert all the values to absolute value for these two columns and save it. Currently I do this

for obj in Product.objects.all():
        obj.price = abs(obj.price)
        obj.sold = abs(obj.sold)
Product.objects.bulk_update(all_obj, ['price', 'sold'])

Although this works, but this takes too long for a table where we can have half a million records. Is there any better way to do this?


Solution

  • As of , you can make use of the Abs function [Django-doc]:

    from django.db.models.functions import Abs
    
    Product.objects.update(price=Abs('price'), sold=Abs('sold'))

    This will do the processing at the database level, not at the Django/Python level, so it will make a query that looks like:

    UPDATE product
    SET price=ABS(price), sold=ABS(sold)