Search code examples
sqldjangomany-to-manydjango-querysetouter-join

Flattened list from manytomany


What is the nicests (quickest) way to create a full outer join on 2 models related by a manytomany field.

for example a book and an author (normally in this case you would use a foreignkey), but suppose a book can have 2 authors (to get my case).

for example:

class Author(models.Model):
    books = models.ManyToManyField(Book,related_name='book_author')

class Book(models.Model):
    title = models.CharField()

and now i want to create a list with: (preferably a queryset)

author1 , book1
author1,  book2
author2,  book1
author2,  book3
author3,  book4

probably because of the time at fridays, but need a bit of help with this...

I want to offer the flat result to an api (DRF), so would be nice to get a queryset of this join.


Solution

  • You are trying to access the auto-generated through model between the Author and Book (Book_authors). You should be able to get that result like this

    >>> Book.authors.through.objects.select_related('book', 'author')
    <QuerySet [<Book_authors: Book_authors object>, ...>
    

    To get the primary keys only, you can use values_list

    >>> Book.authors.through.objects.values_list('book', 'author')
    <QuerySet [(1, 1), (1, 2), (1, 3)]>