Django batch add many to many fields

Time:2020-5-22
class OrderGoodsInfo(models.Model):
    ...
....
class OrderShipping(models.Model):
    order =  models.ManyToManyField (OrderGoodsInfo, blank=True, verbose_ Name = "logistics ID")
....
views.py
container_orders_id = [] 
for order in container_obj.orders.all():
    container_orders_id.append(order.id)
order_goods = OrderGoodsInfo.objects.filter(id__in=container_orders_id)
order_shipping = OrderShipping(user=request.user)
form = OrdershippingForm(request.POST, instance=order_shipping) 
if form.is_valid():
   osp = form.save(commit=False)
   osp.order.add(*order_goods)
   osp.save()
  • See the figure below for deletion and update operations