0

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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Works like a charm! Only i get resposne for my second question and I can sleep peacefully :)
You can override the create() in your Comment's viewset. Pretty easy in the docs. Let me know if you run into any undocumented problems.
Then i can save postId to post but api would return still {post: 1} not postId.. i try use Charfield with source = post but then I lost possibility to select related post from dropdown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.