Coeus
Coeus

Reputation: 2615

Django api returning model ID instead of model's title

Im new to django When I make a api call it shows model.id but I wanted model.titleenter image description here

As we can see that my title is 1 but I wanted the title of the modelnot ID

Model.py

class Post(models.Model):
    title=models.CharField(max_length=200)
    description=models.TextField(max_length=10000)
    pub_date=models.DateTimeField(auto_now_add=True)


    def __unicode__(self):
        return self.title

    def description_as_list(self):
        return self.description.split('\n')

class Comment(models.Model):
    title=models.ForeignKey(Post)
    comments=models.CharField(max_length=200)

    def __unicode__(self):
        return '%s' % (self.title)

views.py

def detail(request, id):
    posts = Post.objects.get(id=id)
    comments=posts.comment_set.all()
    forms=CommentForm
    if request.method == 'POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.title = posts
            print comment
            comment.save()
        else:
          print form.errors
    else:
        form = PostForm()

    return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})

serializer.py

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ('title','comments')

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id','title','description','pub_date')

How can I achieve the title of the blog name instead of just ID

Thanks in advance...

Upvotes: 2

Views: 2037

Answers (2)

zxzak
zxzak

Reputation: 9446

class CommentSerializer(serializers.ModelSerializer):

    title = serializers.CharField(source="title.title", read_only=True)

    class Meta:
        model = Comment
        fields = ('title','comments')

Upvotes: 4

Linovia
Linovia

Reputation: 20986

If you want to get the post's title instead of the id from the CommentSerializer, you'll need to define explicitly the field in the CommentSerializer and use a SlugRelatedField.

Upvotes: 3

Related Questions