Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(post_liked=post.pk, like_author=user.pk)
            print(like)
            obj = LikeSerializer(like).data
            print(obj)
            return JsonResponse(obj)
        return

‘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
print(like)
=> <QuerySet [<Like: flowers, Author, Testuser>]>
obj = LikeSerializer(like).data
print(obj)
=> {'post_liked': None, 'like_author': None}

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

>Solution :

I see the issue in these two lines

like = Like.objects.filter(post_liked=post.pk, like_author=user.pk)
LikeSerializer(like).data

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

OR

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

like = Like.objects.filter(post_liked=post.pk, like_author=user.pk).first()
LikeSerializer(like).data
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading