Thinker
Thinker

Reputation: 5356

django view retrieve all objects of Many-to-Many relationship of foreign key

I have three models as following:

class Library(models.Model):
    library_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.name)

class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    # A book can have multiple authors and an author can have multiple books
    author = models.ManyToManyField('Author')

    # A library has many books
    which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE)

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.title)


class Author(models.Model):
    author_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.name)

I want to retrieve all authors in a specific library. My view looks like following:

@api_view(['GET', 'POST'])
def author_list(request, library_id):
    """
    List all authors in a specific library
    """
    if request.method == 'GET':
        authors = Author.objects.get()
        serializer = AuthorSerializer(books, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = AuthorSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

What should I write in get() as my condition?

UPDATE: my logic is: A library can have many books and a book can have many authors and and an author can have many books.

Upvotes: 3

Views: 1214

Answers (1)

user8060120
user8060120

Reputation:

did you try:

authors = Author.objects.filter(book__which_library_id=library_id).distinct()

more details in docs many_to_many (search text article__headline__)

Upvotes: 2

Related Questions