1

I am trying to create an api endpoint that pulls all the FeaturedProvider and Testimonial objects from the database, serialize it and return it as a new serialized object HomepageContentSerializer

I've tried multiple ways but I'm getting empty {} when I try to hit the endpoint. I'm not sure where to initialize or pass the FeaturedProvider and Testimonial objects to the HomepageContentSerializer to be serialized

serializers.py

class FeaturedProviderSerializer(serializers.ModelSerializer):
    class Meta:
        model = FeaturedProvider
        fields = '__all__'


class TestimonialSerializer(serializers.ModelSerializer):
    class Meta:
        model = Testimonial
        fields = '__all__'


class HomepageContentSerializer(serializers.Serializer):
    providers = FeaturedProviderSerializer(many=True, read_only=True)
    testimonials = TestimonialSerializer(many=True, read_only=True)

views.py

class HomepageContent(APIView):
    renderer_classes = [JSONRenderer]
    def get(self, request):
        content = HomepageContentSerializer().data
        return Response(content)

My goal is to get this representation back

{
    "providers": [
        { ... },
        { ... },
        { ... },
    ],
    "testimonials": [
        { ... },
        { ... },
        { ... },
    ],
}
1
  • You're not passing any data to the serilaizer so of course you get an empty JSON response Commented Jun 3, 2020 at 15:07

1 Answer 1

3

You're not passing any data to the serializer so that is why you are getting an empty JSON response. The serializer does not fetch data from DB on its own. The data gets passed to it. You will also need a data structure that matches the HomepageContentSerializer.

You can use namedtuples.

from collections import namedtuple

HomePageContent = namedtuple('HomePageContent', ['providers', 'testimonials'])

class HomepageContent(APIView):
    renderer_classes = [JSONRenderer]
    def get(self, request):
        providers = Provider.objects.all()
        testimonials = Testimonial.objects.all()
        home_page_data = HomePageContent(providers=providers, testimonials=testimonials)
        content = HomepageContentSerializer(home_page_data).data
        return Response(content)
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, this worked. I wasn't sure how to pass the querysets to HomepageContentSerializer
Glad it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.