all_names = defaultdict(list)
for object in MyModel.objects.all(): # obj1 = John, obj2 = Bob
all_names['name'].append(object)
MyFormSet = modelformset_factory(MyModel, fields=('name'), extra=2)
formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()]
当我跑步时:
[print(form.initial) for form in formset]
我得到:
{'name': <Name: John>}
{} # Where is my second object?
all_names = list() # used a list instead of defaultdict
for object in MyModel.objects.all(): # obj1 = John, obj2 = Bob
d = dict()
d['name'] = object
all_names.append(d)
而不是:
formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()]