在一个查询集中添加多个ManyToManyField对象

时间:2015-06-29 19:03:26

标签: python django django-models django-orm

我有一个django模型结构如下:

class Slot(models.Model):
    timing = models.DateTimeField()

class SlotBooking(models.Model):
    slot = models.ManyToManyField(Slot)
    token = models.CharField()

保存到SlotBooking时,我想知道如果输入插槽是插槽ID数组,是否可以执行以下操作,例如:[1, 2, 3 , 6, 23]

slot_booking = SlotBooking(slot=[array_of_slots], token=value)
slot_booking.save()

如果没有,我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

由于您无法更新相关对象https://docs.djangoproject.com/en/dev/ref/models/querysets/#update

尝试使用通过模型创建批量关系,类似这样(我没有测试过):

from datetime import datetime

slot_id_list = [1, 2, 3 , 6, 23]
slotbooking_obj = SlotBooking.objects.create(timing=datetime.now())

through_model = SlotBooking.slot.through

through_model.objects.bulk_create(map(lambda slot_id: through_model(slotbooking_id=slotbooking_obj.id, slot_id=slot_id), slot_id_list))

https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create

答案 1 :(得分:0)

如果您有项目列表(而不是ID),可以使用以下方法实现:

slot_booking = SlotBooking(token=value)
slot_booking.save()
slot_booking.slot.add(*list_of_slots)