django.db.utils.ProgrammingError: operator does not exist: bigint = uuid

I want to use uuid field as my id (primary key) but there is something wrong with it and i can’t fix it

this is my model

class Cart(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    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']]

This Is MY

class CartItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['id', 'product', 'quantity']

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

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

And My is

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

My database Is postgres Sql
my error is

django.db.utils.ProgrammingError: operator does not exist: bigint = uuid
LINE 1: ..."store_cartitem" WHERE "store_cartitem"."cart_id" IN ('2abf9...
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

There is a stackoverflow post just like this question: postgresql - UUIDField in Django (error:operator does not exist: integer = uuid) - Stack Overflow Does it help?

The error is because uuid are ints and you are comparing them to strings - but the second why (why doesn’t Django know how to create the proper sql to handle the comparison - well that is less clear - the solution suggested in any case seems to be “do it right at the start” (first migration) which is sensible, and barring that seems like you can still use UUIDs as character fields rather than as integer fields.

If the suggested solution doesn’t work and you want to try it, It is possible to reset the database (delete all the migration files, delete the database, and recreate it … that might get everything kicked in right). Personally, I just used integer fields with all my ids - keeping it simple for now :slight_smile: