Django models with OneToOne relationships?

前端 未结 3 1010
南旧
南旧 2021-02-09 12:21

Let\'s say I\'m using the default auth.models.User plus my custom Profile and Address models which look like this:

class P         


        
3条回答
  •  独厮守ぢ
    2021-02-09 12:40

    What about using 3 separate ModelForm. One for Address, one for User, and one for Profile but with :

    class ProfileForm(ModelForm):
      class Meta:
        model = Profile
        exclude = ('user', 'address',)
    

    Then, process these 3 forms separately in your views. Specifically, for the ProfileForm use save with commit=False to update user and address field on the instance :

    # ...
    profile_form = ProfileForm(request.POST)
    if profile_form.is_valid():
      profile = profile_form.save(commit=False)
      # `user` and `address` have been created previously
      # by saving the other forms
      profile.user = user
      profile.address = address
    

    Don't hesitate to use transactions here to be sure rows get inserted only when the 3 forms are valid.

提交回复
热议问题