Home > Software design >  Field 'id' expected a number
Field 'id' expected a number

Time:09-22

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 protected] to it, I get this:

ValueError at /api/get/
Field 'id' expected a number but got '[email protected]'.

CodePudding user response:

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.

  • Related