【问题标题】:How to efficiently add objects to ManyToManyFields of multiple objects Django python?如何有效地将对象添加到多个对象Django python的ManyToManyFields?
【发布时间】:2022-01-05 15:32:53
【问题描述】:

如何高效地将对象添加到多个对象的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)

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2020-11-10
      • 2018-10-05
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多