Search code examples
djangodjango-rest-frameworkdjango-viewsone-to-one

Django reset oneToOneField on Custom User Model


I have a custom User model, which has a one-to-one relationship with a UserProfile model. I want to create a new UserProfile object and switch the existing related UserProfile object with the newly created one.

This is essentially what I am trying to do:

    **views.py**
    def perform_create(self, serializer):
        club = serializer.save(created_by=self.request.user)

        user = self.request.user
        user.current_userprofile = None
        user.save()

        UserProfile.objects.create(
            user_account=self.request.user, 
            club=club, 
            current_active_userprofile=self.request.user, 
            is_admin=True
        )
    **models.py**
    class UserProfile(models.Model):
        user_account = models.ForeignKey(UserAccount, related_name='userprofiles', on_delete=models.CASCADE)
        club = models.ForeignKey(Club, related_name='club_userprofiles', on_delete=models.CASCADE)
        current_active_userprofile = models.OneToOneField(UserAccount, related_name='current_userprofile', on_delete=models.SET_NULL, blank=True, null=True)
        is_admin = models.BooleanField(default=False)

However, the perform_create method triggers an integrity error:

UNIQUE constraint failed: userprofile_userprofile.current_active_userprofile_id

How do I reset the field to NULL so that I can connect it to the newly created object?


Solution

  • You can set the current_active_userprofile to None with:

    def perform_create(self, serializer):
        club = serializer.save(created_by=self.request.user)
    
        user = self.request.user
        current_profile = user.current_userprofile
        current_profile.current_active_userprofile = None
        current_profile.save()
        user.save()
    
        UserProfile.objects.create(
            user_account=self.request.user, 
            club=club, 
            current_active_userprofile=self.request.user, 
            is_admin=True
        )