Ad

Django Model Query All Fields Including The ManyToManyField In A Single Command

- 1 answer

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?

Ad

Answer

You can use prefetch_related for M2M field

Book.objects.select_related('foo').prefetch_related('author').values('author', 'title').get(pk=1)
Ad
source: stackoverflow.com
Ad