'Using CreateView with 2 Models at the same time
should I be building a function to achieve what I am trying to do?
Solution 1:[1]
You should override the form_valid()
method of CreateView. This is called if, well, your form is valid. Then you can create your SetAmount instance there.
Single Exercise Instance
def form_valid(self, form):
# Easy way to obtain the through model (aka SetAmount)
SetAmount = WorkoutRoutine.exercise.through
# Assuming the exercise is selected in the form
exercise = form.cleaned_data['exercise']
# Create a SetAmount instance with the correct workout_routine and exercise from the form
SetAmount.objects.create(
workout_routine=form.instance,
# exercise is a QuerySet, first() will get the instance
exercise=exercise.first(),
set_amount=100 # Swole
)
return super().form_valid(form)
Multiple Exercise Instances with bulk_create
def form_valid(self, form):
# Easy way to obtain the through model (aka SetAmount)
SetAmount = WorkoutRoutine.exercise.through
# Assuming the exercise is selected in the form
exercises = form.cleaned_data['exercise']
# Bulk create relationships by building a list comprehension with exercises cleaned data and passing the list to bulk_create())
SetAmount.objects.bulk_create([
SetAmount(
workout_routine=form.instance,
exercise=exercise,
set_amount=100 # Swole
) for exercise in exercises
])
return super().form_valid(form)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |