Data too long for column 'cart_id' at row 1 - Django


Part-2 Django Course - Designing and Implementing a Shopping Cart API - 5th video
after POSTing a cart item there’s a step of adding the UUID in the database when I do that step I get the error saying “Data too long for column ‘cart_id’ at row 1”. Here are some snippets:
This is image showes the dtype of the columns:
image
store/models.py:

class Cart(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    created_at = models.DateTimeField(auto_now_add=True)


class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items')
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveSmallIntegerField()

    class Meta:
        unique_together = [['cart', 'product']]

store/views.py:

class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = Cart.objects.all()
    serializer_class = CartSerializer

store/serializer.py

class CartSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(read_only=True)

    class Meta:
        model = Cart
        fields = ['id', 'items']

What should be done to avoid this error?

I solved the query, just change the datatype of the id column in store_cart as varchar(36) and same with store_cartitem. :smiling_face_with_three_hearts:

Replace your models.UUIDField to CharField instead. Like this

class Cart(models.Model):
    id=models.CharField(
        primary_key=True,
        default=uuid4, 
        editable=False, 
        max_length=36)
    created_at = models.DateTimeField(auto_now_add=True)
1 Like

You aren’t supposed to change the data type of the column.

Delete the dash when inserting raw data to database.

e.g. 91a9b1e2-f211-49c7-8071-0f62e886261e becomes 91a9b1e2f21149c780710f62e886261e.