While playing around with the ManyToManyField
, I wondered is there a way you can query a ManyToManyField
automatically the same way you'd do a ForeignKey
using select_related()
?
Tables:
class Author(models.Model):
fullname = models.CharField(max_length=100)
class Foo(models.Model):
bar = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
foo = models.ForeignKey(Foo)
author = models.ManyToManyField(Author)
In order to get the data I need from Book
I usually do:
book = Book.objects.select_related('foo').get(pk=1)
authors = book.author.all()
which makes 2 trips. Is there a way to combine them the way select_related()
does?