from django.core.management.base import BaseCommand from tqdm import tqdm from product.models import Product class Command(BaseCommand): help = """Add public_mark to product from reviews.""" def handle(self, *args, **kwarg): update_products = [] products = Product.objects.filter( public_mark__isnull=True, reviews__isnull=False).distinct() for product in tqdm(products): review = product.reviews.published().filter( mark__isnull=False).order_by('-published_at').first() if review: product.public_mark = review.mark update_products.append(product) Product.objects.bulk_update(update_products, ['public_mark', ]) self.stdout.write( self.style.WARNING(f'Updated products: {len(update_products)}'))