1๐
โ
You can create a list where each room appears once for each person it can contain. You can then zip the formset forms and the list together, and create the person for each form.
# 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)
The code may require further changes, for example to handle the case where there are more people than places in rooms.
๐คAlasdair
Source:stackexchange.com