The DRF model serializer returns a dictionary with None values

I'm new to the Django and DRF. My serializer return dict such as: {'Name': None}. I see the same problem, but don't find answer in this. I have the follow model:

class Like(models.Model):
    post_liked = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
    like_author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)

    class Meta:
        unique_together = ("post_liked", "like_author")

    def __str__(self):
        return f'{self.post_liked}, {self.like_author}'

I have the follow simple Serializer:

class LikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Like
        fields = '__all__'

May be it's not enoufh?

My view:

class LikeDetail(View):
    def get(self, request, *args, **kwargs):

        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':

            user = request.user
            post = Post.objects.get(id=kwargs["post_id"])
            like = Like.objects.filter(,
            obj = LikeSerializer(like).data
            return JsonResponse(obj)

'if' is always triggered if it matters. You can see that I using js. Js file have fetch, but problem occurs in serialize process. Example:

user: testuser
post: flowers, Author
=> <QuerySet [<Like: flowers, Author, Testuser>]>
obj = LikeSerializer(like).data
=> {'post_liked': None, 'like_author': None}

I have cheked many sources, but don't find answers.


  • I see the issue in these two lines

    like = Like.objects.filter(,

    Here like is a queryset and not an instance (meaning it may contain more than 1 row in the database, since you are using filter)

    You need to change your line to use many=True

    LikeSerializer(like, many=True).data


    If you expect only 1 row to be returned then you can use .first() this way.

    like = Like.objects.filter(,