Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading