Django 管理命令不工作 cif i 运行 for loop

Django Management Command not workingcif i run for loop

我写了这个管理命令但是没有用

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

class 命令(基础命令):

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}")

您应该使用 id=i 进行过滤,但这会导致大量查询。使用 id__in=ids 进行过滤并在同一个查询中更新所有这些项目会更有效,因此:

    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(<strong>id__in=ids</strong>).update(active=False)
        print(f'The total number of activated ProductName {name}')