Reputation: 6553
I have the following models in an app.
Lesson Student Evaluation Parent
Lesson and Student have a m2m relationship through Evaluation.
I have an inline formset which allows me to create evaluation records at the same time I create a new lesson.
I would like to sort the formset before I process it so that I can put all the records that share a common parent record together and carry out some additional tasks when saving the records.
Here's a simplified example:
EvaluationFormset = inlineformset_factory(Lesson, Evaluation, extra=1, max_num=10)
if request.method == 'POST':
form = LessonForm(request.POST, instance=lesson, user=request.user)
formset = EvaluationFormset(request.POST, instance=lesson)
if form.is_valid() and formset.is_valid():
lesson = form.save()
models = formset.save(commit=False)
#Before I do this, I need to sort the formset based on evaluation.student.parent.
#In the loop, I will perform an additional the first record for each parent
for i in models:
i.user = request.user
i.lesson = lesson
i.save()
Is there any easy way to this in Django?
Any advice appreciated.
Thanks.
Upvotes: 0
Views: 939
Reputation: 5841
Try something like this:
models = list(models) # maybe this can be omitted
models.sort(key=lambda e: e.student.parent)
Upvotes: 1