Django Management Command not workingcif i run for loop

104 views Asked by At

I write this management command but not working

from django.core.management.base import BaseCommand
from name.models import ProductName

class Command(BaseCommand):

def handle(self, *args, **options):

    ids=id[2704, 2709, 2711, 2824, 2825, 2826, 3101, 3102, 3437, 3438, 3439, 3440, 3441, 4256, 4257, 4258, 4260,
            4261, 4262, 4263, 4264, 4265, 4266, 4424, 5125, 17315, 17320, 17322, 17328, 17345, 17356, 17375, 17386,
            17390, 17415, 17425, 17437, 17443, 17445, 17447, 17451, 17454, 17515, 17519, 17525, 17604, 17610, 17624,
            17627, 17634, 17636, 17642, 17648, 17656, 17659, 17680, 17690, 17694, 17700, 17704, 17721, 17724, 17734,
            17737, 17744, 17746, 17749, 17752, 17767, 17780, 17786, 17792, 17798, 17801, 17813, 17837, 17839, 17851,
            17853, 17863, 17881, 17919, 17925, 17945, 17947, 17952, 17955, 17976, 17986, 18016, 18018, 18022, 18030,
            18040, 18046, 18055, 18066, 18072, 18108, 18155, 18163, 18173, 18188, 18205, 18211, 18221, 18234, 18247,
            18260, 18273, 18294, 18297, 18321, 18519]
    for i in ids:
        name = ProductName.objects.filter(i).update(active=False)
        print(f"The total number of activated ProductName {name}")
1

There are 1 answers

0
willeM_ Van Onsem On BEST ANSWER

You should filter with id=i, but that would result in a lot of queries. It is more efficient to filter with id__in=ids, and update all of these items in the same query, so:

    def handle(self, *args, **options):
        ids = [2704, 2709, 2711, 2824, 2825, 2826, 3101, 3102, 3437, 3438, 3439, 3440, 3441, 4256, 4257, 4258, 4260,
                4261, 4262, 4263, 4264, 4265, 4266, 4424, 5125, 17315, 17320, 17322, 17328, 17345, 17356, 17375, 17386,
                17390, 17415, 17425, 17437, 17443, 17445, 17447, 17451, 17454, 17515, 17519, 17525, 17604, 17610, 17624,
                17627, 17634, 17636, 17642, 17648, 17656, 17659, 17680, 17690, 17694, 17700, 17704, 17721, 17724, 17734,
                17737, 17744, 17746, 17749, 17752, 17767, 17780, 17786, 17792, 17798, 17801, 17813, 17837, 17839, 17851,
                17853, 17863, 17881, 17919, 17925, 17945, 17947, 17952, 17955, 17976, 17986, 18016, 18018, 18022, 18030,
                18040, 18046, 18055, 18066, 18072, 18108, 18155, 18163, 18173, 18188, 18205, 18211, 18221, 18234, 18247,
                18260, 18273, 18294, 18297, 18321, 18519]
        name = ProductName.objects.filter(id__in=ids).update(active=False)
        print(f'The total number of activated ProductName {name}')