Opened 5 years ago

Closed 5 years ago

#30368 closed Bug (fixed)

Prefetch related is not working when used GFK for model that uses FK as PK.

Reported by: Vinny Do Owned by: Vinny Do
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: prefetch_related genericforeignkey
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Steps to reproduce

Create Base model with an AutoField primary key

class Base(models.Model):
    title = models.TextField()

Create a model where the primary key is also a foreign key

class Extended(models.Model):
    base = models.OneToOneField(Base, on_delete=models.CASCADE, primary_key=True)

Create model with GenericForeignKey

class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_pk = models.TextField()
    content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")

Prefetch the GenericForeignKey field content_object expecting it to have a value but get None instead.

# Setup
base = Base.objects.create(title="foo")
extended = Extended.objects.create(base=base)
Comment.objects.create(content_object=extended)

# Exercise
comment = Comment.objects.prefetch_related("content_object").get()
print(comment.content_object)

Change History (3)

comment:1 by Vinny Do, 5 years ago

Has patch: set

comment:2 by Mariusz Felisiak, 5 years ago

Owner: changed from nobody to Vinny Do
Status: newassigned
Summary: prefetch_related does not work for GenericForeignKey field when its primary key is also a foreign keyPrefetch related is not working when used GFK for model that uses FK as PK.
Triage Stage: UnreviewedAccepted

comment:3 by Mariusz Felisiak <felisiak.mariusz@…>, 5 years ago

Resolution: fixed
Status: assignedclosed

In a4055adf:

Fixed #30368 -- Fixed prefetch_related() for GenericForeignKey when PK is also a FK.

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