Django как создать объект и добавить многие ко многим лучший способ или лучшая практика

как я могу сделать этот код намного эффективнее или быстрее

    def handle(self, *args, **kwargs):
        shops = MyShop.objects.all()
        for shop in shops:
            month_invoice = shop.shop_order.annotate(year=TruncYear('created'), month=TruncMonth('created')).values(
            'year', 'month', 'shop_id'
        ).annotate(total=Sum(ExpressionWrapper(
            (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())),
        ).order_by('month')
        for kv in month_invoice:
            a = ShopInvoice.objects.create(shop_id=kv['shop_id'], year=kv['year'], month=kv['month'], total=kv['total'])
            test = shop.shop_order.filter(created__month=kv['month'].month, created__year=kv['year'].year)
            for t in test:
                a.items.add(t.id)
Вернуться на верх