Sierran
Sierran

Reputation: 117

Django Rest Framework return True if relation exist

I have two questions. How i can just return true if relation exist? For example I have post model and comment model also, comment have foreginKey to post. Now after post serialization i wanna have something like this

{
id: 2
content: "My first post!"
has-comments: True
}

And my second question is how rename field name in model relation? Again we have post and comment. In comment model i have foregin key to post like

post = models.ForeignKey(Post)

Now when i add new comment i send JSON data with {post: postIdHere}. Is possible to change post to postId only in drf not in django model?

I hope you understand me :) Best Redgards, Sierran.

Upvotes: 0

Views: 452

Answers (1)

Brian
Brian

Reputation: 7654

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.

Upvotes: 1

Related Questions