Search code examples
pythondjangodjango-rest-frameworkdjango-viewsdjango-serializer

Serializing model queryset showing empty [OrderedDict()]


I am building a blog app with React and Django and I am serializing model's instances saved by particular user, First I am just trying to test with .all() then I am planning to filter by specific user But when I serialize queryset with Serializer like:

class BlogSerializerApiView(viewsets.ModelViewSet):
    serializer_class = BlogSerializer

    def get_queryset(self, *args, **kwargs):
        queryset = Blog.objects.all()
        output_serializer = BlogSerializer(queryset, many=True)
        print(output_serializer.data)
        return "Testing"

It is showing in console:

[OrderedDict(), OrderedDict()]

and when I access it like

print(output_serializer)

Then it is showing:

BlogSerializer(<QuerySet [<Blog: user_1 - Blog_title>, <Blog: user_2 - second_blog_title>]>, many=True):

serializer.py:

class BlogSerializer(serializers.Serializer):
    class Meta:
        model = Blog
        fields = ['title']

models.py:

class Blog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30, default='')

    def __str__(self):
        return f"{self.user} - {self.title}"

What I am trying to do:

I am trying to serialize queryset to show on page in react frontend, I will relate with specific user later.

I have tried many times by changing CBV serialization method by generics.ListAPIView instead of viewsets.ModelViewSet but still same thing.


Solution

  • I was using

    class BlogSerializer(serializers.Serializer):
        .......
    

    so it was showing empty results (no idea why, I think its deprecated)

    After replaceing it with

    class BlogSerializer(serializers.HyperlinkedModelSerializer):
    

    It worked