#33651: Support prefetch GenericForeignKey with custom queryset.
-------------------------------------+-------------------------------------
Reporter: elonzh | Owner: nobody
Type: New feature | Status: new
Component: Database layer | Version: 4.0
(models, ORM) |
Severity: Normal | Resolution:
Keywords: GenericForeignKey | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):
If I understand correctly you'd like to be able to have the prefetch
querysets issued when doing
`Node.objects.prefetch_related('content_object')` for `ItemA` and `ItemB`
be `.objects.only('name')`.
I've had to implement such a feature in the past and ended up with writing
[https://gist.github.com/charettes/3dcdec3bf66257b0299455a70559f47d my
own] `GenericForeignKeySubclass` that would allow for the following
{{{#!python
class Node(models.Model):
content_type = models.ForeignKey(ContentType,
on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = PrefetchedManagerGenericForeignKey("name_only",
"content_type", "object_id")
class AbstractNodeItem(models.Model):
name = models.CharField(max_length=100)
class NameOnlyManager(models.Manager):
def get_queryset(self):
return super().only("name")
class ItemA(AbstractNodeItem):
a_content = models.TextField()
name_only = NameOnlyManager()
class ItemB(AbstractNodeItem):
b_content = models.TextField()
name_only = NameOnlyManager()
}}}
If we were to do a proper implementation here though I think that a
`GenericPrefetch(Prefetch)` subclass would make for a better API as that's
the current way custom querysets are provided to the prefetching logic.
Something along
{{{#!python
Node.objects.prefetch_related(
GenericPrefetch(
"content_object", querysets={
ItemA: ItemA.objects.only("a"),
ItemB: ItemB.objects.only("a"),
}
)
)
}}}
Accepting on the basis that I think this would be a valuable feature.
--
Ticket URL: <https://code.djangoproject.com/ticket/33651#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/010701803d1ac285-a7b8f8ee-3d39-401c-84d1-5ea9bf221e0e-000000%40eu-central-1.amazonses.com.