Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-serializerdjango-rest-viewsets

making an api to show the books of an auther in django rest framework


I have two models in my project: Author and Book. Each book has a foreignkey that points to the author of the book. I want to write an api which retrieves and instance of an Author and shows the details of that specific person. The problem is that I don't know how to include that said person's books in my API.

This is my models.py:

class Book(models.Model):
    title = models.CharField(max_length=150)
    rating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),])
    summary = models.TextField()
    author = models.ForeignKey(Author, null=True, on_delete=models.SET_NULL)


class Author(models.Model):
    authorID = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    dateOfBirth = models.DateField(null=True)
    nationality = models.CharField(null=True, max_length=255)

AND this is the method that didn't work for me:

# Serializers.py
class AuthorRetrieveSerializer(serializers.ModelSerializer):
    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = '__all__'

    bookDetails = BookSerializer(read_only=True, many=True)
    class Meta:
        model = Author
        fields = ('name', 'dateOfBirth', 'nationality', 'bookDetails')

# Views.py
class AuthorRetrieveViewSet(RetrieveUpdateDestroyAPIView):
    permission_classes = (AllowAny,)
    serializer_class = serializers.AuthorRetrieveSerializer
    queryset = Author.objects.all()
    lookup_field = 'authorID'

    def get_queryset(self):
        return self.queryset

This code retrieves the Author details successfully but doesn't give me their Books.


Solution

  • Have you tried specifying the source on the serializer?

    # Serializers.py
    class BookSerializer(serializers.ModelSerializer):
                class Meta:
                    model = Book
                    fields = '__all__'    
    
    class AuthorRetrieveSerializer(serializers.ModelSerializer):
            
            bookDetails = BookSerializer(read_only=True, many=True, source="book_set")#correction here
            class Meta:
                model = Author
                fields = ('name', 'dateOfBirth', 'nationality', 'bookDetails')