0

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?

enchance
  • 29,075
  • 35
  • 87
  • 127
  • Possible duplicate of [What's the difference between select\_related and prefetch\_related in Django ORM?](https://stackoverflow.com/questions/31237042/whats-the-difference-between-select-related-and-prefetch-related-in-django-orm) – Endre Both Apr 27 '19 at 07:39

1 Answers1

0

You can use prefetch_related for M2M field

Book.objects.select_related('foo').prefetch_related('author').values('author', 'title').get(pk=1)
shafik
  • 6,098
  • 5
  • 32
  • 50