Django ModelForm: What is save(commit=False) used for?

后端 未结 5 1530
遇见更好的自我
遇见更好的自我 2020-11-28 20:51

Why would I ever use save(commit=False) instead of just creating a form object from the ModelForm subclass and running is_valid() to v

5条回答
  •  独厮守ぢ
    2020-11-28 21:29

    As a "real example", consider a user model where the email address and the username are always the same, and then you could overwrite your ModelForm's save method like:

    class UserForm(forms.ModelForm):
        ...
        def save(self):
            # Sets username to email before saving
            user = super(UserForm, self).save(commit=False)
            user.username = user.email
            user.save()
            return user
    

    If you didn't use commit=False to set the username to the email address, you'd either have to modify the user model's save method, or save the user object twice (which duplicates an expensive database operation.)

提交回复
热议问题