Django - 使用不同的值保存formset数据

时间:2017-03-29 08:51:32

标签: django django-forms

我有这样的模特:

class House(models.Model):
  name = models.CharField(max_length=50, blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.name

class Rooms(models.Model):
  house = models.ForeignKey(House, null=True)
  room = models.CharField(max_length=50, blank=True, null=True)
  people = models.IntegerField(blank=True, null=True)

  def __unicode__(self):
    return '%s' % self.room

class People(models.Model):
  room = models.ForeignKey(Rooms, null=True)
  name = models.CharField(max_length=30)
  surname = models.CharField(max_length=50)

  def __unicode__(self):
    return '%s' % self.surname

因此,如果在房子里有两个房间,每个房间有两个人,我需要用一个People密钥保存两个room个实例,用另一个room密钥保存第二个People个实例而不是这个我的代码在每个Rooms中保存了四个for people in people_formset: name = adult_tourists.cleaned_data['name'] surname = adult_tourists.cleaned_data['surname'] for room in house.rooms_set.all(): for people in range(room.people): p = People.objects.create(room=room, name=name, surname=surname) p.save() 个实例。

我的代码如下所示:

msbuild ConsoleApp.sln

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以创建一个列表,其中每个房间可以为其包含的每个人显示一次。然后,您可以将formset表单和列表压缩在一起,并为每个表单创建人员。

# creates a list of lists e.g. [[room1, room1], [room2], [room3]]
room_lists = [[room] * room.people for room in house.rooms_set.all()]

# flatten the list e.g. [room1, room1, room2, room3]
rooms = [room for room_list in room_lists for room in room_list]

# zip the lists together
for form, room in zip(people_formset, rooms):
    name = form.cleaned_data['name']
    surname = form.cleaned_data['surname']
    p = People.objects.create(room=room, name=name, surname=surname)

代码可能需要进一步更改,例如处理人数多于房间内人数的情况。