Field 'id' expected a number

I’ve defined my custom user model as below (to have email as username):

class User(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    objects = UserManager()

    def __str__(self):
        return self.email
        

And Profile model in api app as below:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verified = models.BooleanField(default=False)

    def __str__(self):
        return self.user.email

This is the serilizer:

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ['user', 'verified']

And the view:

@api_view(['POST'])
def get_user(request):
    email = request.data['email']
    user = Profile.objects.get(user=email)
    serializer = ProfileSerializer(user)
    return Response(serializer.data)

But when I call get_user and post email=myuser@mydomain.com to it, I get this:

ValueError at /api/get/
Field 'id' expected a number but got 'myuser@mydomain.com'.

>Solution :

this is because user is a foreign key which links to user’s id. If you need to filter by user email you need to rewrite your query to this Profile.objects.get(user__email=email):

@api_view(['POST'])
def get_user(request):
    email = request.data['email']
    user = Profile.objects.get(user__email=email)
    serializer = ProfileSerializer(user)
    return Response(serializer.data)

See details about filtering by related object here.

Leave a Reply