﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
33450	Integer primary key is wrongly casted to UUID when filtering GenericRelation on model with UUID primary key.	Santos Gallegos	Clifford Gama	"Hi, at Read the Docs we have migrated from Django 2.2 to 3.2, and we encountered the following problem. In a model that makes use of a GenericForeignKey field, and it has a UUID field as its pk will result in Django casting the ID of the related model as UUID in some queries (the related model makes use of the default BigAutoField). I was able to reproduce this with the following models and using postgres as the DB backend.


{{{#!python
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import (
    GenericForeignKey,
    GenericRelation,
)
import uuid

class TTag(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content = GenericForeignKey()


class TIntegration(models.Model):
    tags = GenericRelation(TTag, related_query_name='integration')
}}}


The problematic queries:


{{{#!python
integration = TIntegration.objects.create()
tag = integration.tags.create()
r = TTag.objects.filter(integration=integration)
print(r.query)

# The next error is raised if the query is evaluated
# psycopg2.errors.UndefinedFunction: operator does not exist: bigint = uuid
}}}

The query will result in the following SQL



{{{#!sql
SELECT ""core_ttag"".""id"", ""core_ttag"".""content_type_id"", ""core_ttag"".""object_id"" FROM ""core_ttag"" INNER JOIN ""core_tintegration"" ON (""core_ttag"".""object_id"" = ""core_tintegration"".""id"" AND (""core_ttag"".""content_type_id"" = 7)) WHERE ""core_tintegration"".""id"" = 00000000-0000-0000-0000-000000000001
}}}


Note as `core_tintegration"".""id""` is being casted as an UUID when it should be an integer (1). I was able to bisect the error to this commit https://github.com/django/django/commit/1afbc96a75bd1765a56054f57ea2d4b238af3f4d. Before that commit, the generated SQL is as follows:



{{{#!sql
SELECT ""core_ttag"".""id"", ""core_ttag"".""content_type_id"", ""core_ttag"".""object_id"" FROM ""core_ttag"" INNER JOIN ""core_tintegration"" ON (""core_ttag"".""object_id"" = ""core_tintegration"".""id"" AND (""core_ttag"".""content_type_id"" = 7)) WHERE ""core_tintegration"".""id"" = 1
}}}


We were able to work around this issue by changing the queries to explicitly use the ID.

{{{#!python
TTag.objects.filter(integration__id=integration.id)
}}}"	Bug	assigned	contrib.contenttypes	4.0	Normal			Timur Chinmoy	Accepted	1	0	0	1	0	0
