同时对 2 个模型使用 CreateView

Using CreateView with 2 Models at the same time

我应该构建一个函数来实现我想要做的事情吗?

您应该覆盖 CreateView 的 form_valid() 方法。如果您的表单有效,则称为此。然后你可以在那里创建你的 SetAmount 实例。

单个练习实例

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)

多个练习实例 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)