从django表单创建多个相同的对象

时间:2016-06-27 10:46:57

标签: django django-forms

由于用户在Django中完成单个表单,创建多个相同对象的最佳方法是什么?

如果我在一个循环中调用form.save()(基于一个由表单或其他东西设置的集合号),它只会多次创建一个具有相同ID的实例。

我实际上要做的是根据一系列用户指定的日期(目前使用django-recurrence)创建一组相同的实例,每天/每周/任何事情。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您正在寻找Django的atomic transactions。然后复制模型实例using pk=None以创建副本:

from django.db import IntegrityError, transaction

def save(self, commit=False):
    model1 = super(YourForm, self).save(commit=False)    
    try:
        with transaction.atomic():
            model1.save()
            model1.pk = None
            model1.save() # Saves the second instance, you can loop this.
    except IntegrityError:
        handle_exception()

    return model1

编辑 - 如果速度是您的问题,您可以使用bulk_create,如下所示:

def save(self, commit=False):
    number_of_objects = range(10) # How many objects you want to save
    n = 0
    model1 = super(YourForm, self).save(commit=False)
    objs = [
        YourModel(
            attribute1=model1.attribute1, 
            attribute2=model1.attribute2
        )
        for obj in number_of_objects
    ]
    YourModel.objects.bulk_create(objs)

答案 1 :(得分:0)

我需要为多个客户端发布提醒,具体取决于创建提醒时是否选中了该复选框。 Deepcopy使单独的对象=数据库中的单独行。

from copy import deepcopy

... in a function based view....
if request.method == 'POST':
    form = NoticeForm(request.POST)
    if form.is_valid():
        # municipalities is a checkbox list on the screen
        municipalities_id_list = request.POST.getlist('municipalities')
        municipalities = Group.objects.filter(id__in=municipalities_id_list)

        for gm in municipalities:
            notic = deepcopy(form.save(commit=False))
            notic.id = None    # let Django assign a new id when doing the save
            notic.client = gm
            notic.last_modified_user = user
            notic.save()