1

I would like to extend the user model with attributes that are specific to the application, in this case I am simply substituting them with extA and extB. I have made a model to extend the user model and I have created a simple serializer for that model. Now I'm not sure how to create the user with the extra fields.

models.py

class UserDetails(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    extA = models.IntegerField(null=True)
    extB = models.IntegerField(null=True)

@receiver(post_save, sender=User)
def handle_user_save(sender, instance, created, **kwargs):
    if created:
        UserDetails.objects.create(user=instance)

serializers.py

class UserDetailsSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'extA', 'extB')

views.py

class UserDetailsView(APIView):

    def get(self, request, id, format=None):
        data = User.objects.get(id)
        serializer_class = UserDetailsSerializer
        return Response(serializer_class.data)

I have been creating users via the shell. Like this: user = User.objects.create_user('John', '[email protected]', 'pass'). This works really well but I'm not sure how to create a UserDetailsView object and save it.

1 Answer 1

2

To create UserDetails in your view

 user = User.objects.get(id=id)
 UserDetails.objects.create(id=user.id,user=user,extA=your_val_1,extB=your_val_2)

And then you should be able to refer it as user.userdetails.extA, user.userdetails.extB

Sign up to request clarification or add additional context in comments.

2 Comments

Running this command in the shell I am getting: IntegrityError: UNIQUE constraint failed: app_userdetails.user_id. Do you know what could be causing that?
It means the id you're providing already exists. Delete it with UserDetails.objects.get(id=id).delete() or provide an id that is not there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.