Create `Base` model with an `AutoField` primary key
{{{#!python
class Base(models.Model):
title = models.TextField()
}}}
Create a model where the primary key is also a foreign key
{{{#!python
class Extended(models.Model):
base = models.OneToOneField(Base, on_delete=models.CASCADE,
primary_key=True)
}}}
Create model with `GenericForeignKey`
{{{#!python
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.
{{{#!python
# 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)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/30368>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* has_patch: 0 => 1
--
Ticket URL: <https://code.djangoproject.com/ticket/30368#comment:1>
* status: new => assigned
* owner: nobody => Vinny Do
* stage: Unreviewed => Accepted
Comment:
[https://github.com/django/django/pull/11234 PR]
--
Ticket URL: <https://code.djangoproject.com/ticket/30368#comment:2>
* status: assigned => closed
* resolution: => fixed
Comment:
In [changeset:"a4055adf702d086334a9ab2ca25a5e41e896a4fb" a4055adf]:
{{{
#!CommitTicketReference repository=""
revision="a4055adf702d086334a9ab2ca25a5e41e896a4fb"
Fixed #30368 -- Fixed prefetch_related() for GenericForeignKey when PK is
also a FK.
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/30368#comment:3>