提交表单时如何创建同一模型的多个实例?

时间:2016-03-03 19:45:21

标签: python django django-models django-views

我有以下型号:

class EventType(models.Model):
    name = models.CharField(max_length=128)

class Event(models.Model):
    event = models.ForeignKey(EventType, null=True, blank=True)
    name = models.CharField(max_length=128)
    is_multiple = models.BooleanField(default=False)
    father_event = models.ForeignKey('self', null=True, blank=True)
    event_multiple = models.ManyToManyField(EventType, null=True, blank=True)

    def save(self, *args, **kwargs):
        if self.name == None or self.name == '':
            self.name = self.event.name + ' - blabla'
        super(Event, self).save(*args,**kwargs) 

我需要从EventType到Event的两个关系,因为如果is_multiple = True,我想添加多个事件类型。

基本上,如果一个事件是多个,它包含许多事件。所以,我需要为表单中选择的每个EventType创建一个新事件。例如:

MultiEvent 1, is_multiple = True:
    In the form, selects 3 EventType = TypeA, TypeB, TypeC
    When I save, it creates 3 Events = TypeA - blabla, TypeB - blabla, TypeC - blabla

Each of those events has father_event = MultiEvent 1

我需要帮助实现这一目标。也许你知道一个更好的方法来做到这一点。

任何帮助都将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

我会做那样的事情

class EventType(models.Model):
    name = models.CharField(max_length=128)


class Event(models.Model):
    kind = models.ForeignKey(EventType, null=True, blank=True)
    name = models.CharField(max_length=128)
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True)

###

type_list = []
for name in ('TypeA', 'TypeB', 'TypeC'):
    type_list.append(EventType.objects.create(name=name))


obj = Event.objects.create(
    kind=None, 
    name='Sample MultiEvent', 
    parent=None
)

for i, kind in enumerate(type_list):
    tmp = Event.objects.create(
        kind=kind, 
        name='Subevent {0}.{1}'.format(obj.pk, i),
        parent=obj
    )

is_event_multiple = obj.children is not None