'RetrieveUpdateAPIView Field 'id' expected a number but got <User: Chris>
I am trying to update a customer with Django Rest Framework but I get this error:
Field 'id' expected a number but got <User: Chris>.
'Chris' is the username of the user.
If I remove the 'pk' and 'accounts' for the serializer it will not be a problem, but I need those properties for an other function to work.
It says that the property full_name from customer expected an number but got user, which makes sense but how do I then convert it to the user 'id'?
return f'{self.user.first_name} {self.user.last_name}'
Error in formatting: TypeError: Field 'id' expected a number but got <User: Chris>.
This is my class-based view using RetrieveUpdateAPIView
class staff_customer_details(generics.RetrieveUpdateAPIView):
serializer_class = CustomerSerializer
permissions_classes = [permissions.IsAuthenticated, ]
queryset = Customer.objects.all()
and the model and serializer looks like this:
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.PROTECT)
rank = models.CharField(choices=RANK_CHOICES, max_length=7)
personal_id = models.IntegerField(db_index=True)
phone = models.CharField(max_length=35, db_index=True)
@property
def full_name(self) -> str:
return f'{self.user.first_name} {self.user.last_name}'
class CustomerSerializer (serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True)
accounts = AccountSerializer(many=True, read_only=True)
class Meta:
fields = ('user', 'pk', 'rank', 'personal_id', 'phone', 'accounts', 'can_make_loan', 'full_name')
model = Customer
Solution 1:[1]
I think the reason is that you set primary_key = True in user field of the Customer model.
Please remove that attribute.
Then django will set the default primary_key field, that is id, in the Customer model.
And in CustomerSerializer, the pk should be changed into id.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sunderam Dubey |
