Opened 6 years ago

Closed 6 years ago

#29314 closed Bug (duplicate)

PostgreSQL error when using a TextField generic object ID field, an integer PK, and GenericRelation

Reported by: Kye Russell Owned by: nobody
Component: contrib.contenttypes Version: 1.11
Severity: Normal Keywords: orm, postgres
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I'm still unsure if this is a Django bug or incorrect usage on my part, so please close this ticket if it's the latter.

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?

Change History (1)

comment:1 by Tim Graham, 6 years ago

Component: Database layer (models, ORM)contrib.contenttypes
Resolution: duplicate
Status: newclosed

Duplicate of #16055.

Note: See TracTickets for help on using tickets.
Back to Top