I have the following models (greatly simplified)
class Species(models.Model):
# automatic primary key: id, bigint
label = models.CharField(
null=True, blank=True,
max_length=LABEL_LENGTH
)
photos = GenericRelation(Photo, related_query_name='species')
class FieldNotes(models.Model)
fulcrum_id = models.CharField(
max_length = EXTERNAL_ID_LENGTH,
primary_key=True
)
scan_name = models.CharField(
max_length=LABEL_LENGTH,
)
photos = GenericRelation(Photo, related_query_name='species')
class Media(models.Model):
# automatic primary key: id, bigint
caption = models.TextField(
blank=True, default='',
)
object_id = models.CharField(
max_length = EXTERNAL_ID_LENGTH,
)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abstract = True
class Photo(Media):
photo= models.ImageField(
upload_to ='photo/%Y/%m/',
)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
related_name="photos")
class Video(Media):
video = models.FileField(
null=True, blank=True,
upload_to='videos/', )
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
related_name="videos")
This works generally fine, but when I want to query for example Species that have a photo with a certain caption
qs = Species.objects.filter(photos__caption='abc')
I get the following error:
django.db.utils.ProgrammingError: operator does not exist: bigint = character varying
Obviously this comes from the mismatch between foreign key and primary key types, varchar vs bigint.
If I do the same query for model FieldNotes it works
qs = FieldNotes.objects.filter(photos__caption='abc')
Question: Django documentation (https://docs.djangoproject.com/en/4.2/ref/contrib/contenttypes/
) states that:
Primary key type compatibility
The “object_id” field doesn’t have to be the same type as the primary key fields on the related models, but their primary key values must be coercible to the same type as the “object_id” field by its get_db_prep_value() method.
So this should work, why doesn't it? Is there a way I make it work without changing the primary key type in FieldNotes (and other similar models)?