I have a fairly basic looking Django model with a generic relationship:
{{{
class AttachedMediaItem(models.Model):
# Generic relation to another object.
parent_content_type = models.ForeignKey(
'contenttypes.ContentType',
related_name='attachedmediaitem_parent_set',
on_delete=models.CASCADE)
parent_object_id = models.TextField(db_index=True)
parent_content_object = GenericForeignKey('parent_content_type',
'parent_object_id')
}}}
(irrelevant fields removed)
I inherited this codebase so I cannot fully justify all design decisions,
however I believe parent_object_id is a TextField to support non-integer
PKs on the related object (e.g. UUIDs). This model tends to relate to a
wide variety of other models, so it needs to be very versatile in terms of
what PK types it supports.
This is as-per the Django docs recommendations:
https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericForeignKey
Now, this model:
{{{
class UnitType(models.Model):
media = GenericRelation('media.AttachedMediaItem',
content_type_field='parent_content_type',
object_id_field='parent_object_id')
}}}
(irrelevant fields removed).
Note that I'm leaving the PK generation up to Django, meaning I'll get an
integer PK for this model.
Now, if I run this
{{{
UnitType.objects.filter(media__isnull=True)
}}}
An SQL error manages to bubble through the ORM:
{{{
ProgrammingError: operator does not exist: integer = text
LINE 1: ...a_attachedmediaitem" ON ("products_unittype"."id" = "media_a...
^
HINT: No operator matches the given name and argument type(s). You might
need to add explicit type casts.
}}}
My understanding is that this is due to the difference in PK fields.
I believe I have followed the prescribed best practice as per the Django
documentation (relevant section linked above). I feel that at the very
least this shouldn't result in a somewhat cryptic PostgreSQL error.
Is this a genuine Django bug, or misuse on my part?
--
Ticket URL: <https://code.djangoproject.com/ticket/29314>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* status: new => closed
* component: Database layer (models, ORM) => contrib.contenttypes
* resolution: => duplicate
Comment:
Duplicate of #16055.
--
Ticket URL: <https://code.djangoproject.com/ticket/29314#comment:1>