Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Filter Select_Related

Tags:

django

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.

like image 497
AgDude Avatar asked Jan 17 '23 15:01

AgDude


1 Answers

You cannot do this with select_related as it will only work for One-to-One fields or ForeignKeys. For reverse relationships like this, the development version has introduced prefetch_related which is exactly what you're looking for.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

like image 55
Spike Avatar answered Jan 24 '23 13:01

Spike