如何高效地将对象添加到多个对象的ManyToManyFields Django python?

How to efficiently add objects to ManyToManyFields of multiple objects Django python?

如何高效地将对象添加到多个对象的ManyToManyFields中?

    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)

.add() 方法接受多个对象添加。我没有看过这个 Django 源代码,但我希望如果有任何可能的优化,它就会完成。所以试试

a.items.add( *[ t.id for t in test ] )

如果您安装了 Django 调试工具栏,您可以非常快速地查看它是否经过优化(通常是一个数据库操作而不是 N = len(test) )