[Fixed]-Django Rest Framework return True if relation exist

1👍

The closest thing I can come up with is a custom has_comments field (rather than has-comments) with this in the serializer:

from rest_framework import serializers

class YourSerializer(Either Serializer or ModelSerializer...):
    has_comments = serializers.SerializerMethodField()
    @staticmethod
    def get_has_comments(instance):
        # Choose whichever one works for you.
        # You did not specify some model names, so I am just making stuff up.
        return instance.post_set.exists()
        return Comment.objects.filter(post_id=instance.id).exists()

You may also have to specify the field in the serializer’s Meta class. When first run, the framework will tell you exactly how.

👤Brian

Leave a comment