When using select_related, has anyone developed a way to filter on a field in the foreign key table.
For example given these models:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
class AuthorExtra(models.Model):
author = models.ForeignKey(Author)
type = models.ForeignKey(ExtraType)
value = models.CharField(max_length = 24)
I would like a way to cache all of the related AuthorExtra objects of a specific type.
You cannot do this with
select_relatedas it will only work for One-to-One fields or ForeignKeys. For reverse relationships like this, the development version has introducedprefetch_relatedwhich is exactly what you’re looking for.https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related