gpt4 book ai didi

python - Django api 返回模型 ID 而不是模型的标题

转载 作者:行者123 更新时间:2023-12-02 15:21:34 25 4
gpt4 key购买 nike

我是 django 的新手 当我调用 api 它显示 model.id 但我想要 model.title enter image description here

我们可以看到我的标题是 1 但我想要的是模型的标题而不是 ID

模型.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)

View .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})

序列化器.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')

如何实现博客名称的标题而不仅仅是ID

提前致谢...

最佳答案

class CommentSerializer(serializers.ModelSerializer):

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

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

关于python - Django api 返回模型 ID 而不是模型的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36055460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com