#37201: Prefetch with to_attr silently ignored if matching property exists
-------------------------------------+-------------------------------------
Reporter: dc-strahlkraft | Type: Bug
Status: new | Component: Database
| layer (models, ORM)
Version: 6.0 | Severity: Normal
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Minimal reproduction
https://gitlab.com/Dan_Strahlkraft/django-prefetch
Given these models:
{{{
class Product(models.Model):
@property
def enabled_images(self):
return self.images.filter(enabled=True)
class ProductImage(models.Model):
product = models.ForeignKey(Product, models.PROTECT,
related_name="images")
enabled = models.BooleanField()
}}}
I want to eagerly load the `enabled_images` property so that it doesn't
hit the database on access. So I write:
`Product.objects.prefetch_related(Prefetch("images",
ProductImage.objects.filter(enabled=True), to_attr="enabled_images"))`.
But that doesn't prefetch anything. The Prefetch is silently ignored.
The simplest workaround I can think of is:
{{{
class Product(models.Model):
@property
def enabled_images(self):
try:
return self.prefetched_enabled_images
except AttributeError:
return self.images.filter(enabled=True)
}}}
Then I can write `Product.objects.prefetch_related(Prefetch("images",
ProductImage.objects.filter(enabled=True),
to_attr="prefetched_enabled_images"))` and now accessing
`product.enabled_images` won't hit the database, but I think it's uglier.
--
Ticket URL: <
https://code.djangoproject.com/ticket/37201>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.