我有 django api,其中我有帖子模型,该模型通过 forgin 键链接到评论和类别表,现在我正在获取帖子详细信息的数据,当我尝试访问该帖子的类别时,它返回 s id,我想访问的名称类别这是我的帖子列表视图
{
"id": 4,
"title": "BLOG PAGE",
"body": "testing",
"owner": "ankit",
"comments": [],
"categories": [
2
],
"created_at": "2021-05-07T17:22:32.989706Z"
},
{
"id": 5,
"title": "Test Post",
"body": "This is a test Post",
"owner": "ankit",
"comments": [],
"categories": [
2
],
这是我的类别
[
{
"id": 2,
"name": "Python",
"owner": "ankit",
"posts": [
4,
5,
6,
8
]
}
]
这是我的帖子详细信息组件
export class PostDetail extends React.Component {
constructor(props) {
super(props);
const ID = this.props.match.params.id
this.state = {
data: [],
loaded: false,
placeholder: "Loading"
};
}
formatDate(dateString){
const options = { year: "numeric", month: "long", day: "numeric" }
return new Date(dateString).toLocaleDateString(undefined, options)
}
componentDidMount() {
fetch(`${Url}posts/${this.props.match.params.id}`)
.then(response => {
if (response.status > 400) {
return this.setState(() => {
return { placeholder: "Something went wrong!" };
});
}
return response.json();
})
.then(data => {
this.setState(() => {
return {
data,
loaded: true
};
});
});
}
render(){
return(
<>
<h1 className="main-title">{this.state.data.title}</h1>
<div className="container">
<div className="box1">
<h2>Categories</h2>
<div className="categories">{this.state.data.categories}</div>
</div>
</>
);
}
}
当我尝试获取上面提到的数据时,我得到的输出为 2 我认为我可以通过将其放在例如.
前面来访问它categories
。categories.name
但它返回TypeError
错误
TypeError: Cannot read property 'name' of undefined
这是我的 serializers
class CategorySerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Category
fields = ['id', 'name', 'owner', 'posts']
class PostSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Post
fields = ['id', 'title', 'body', 'owner', 'comments', 'categories','created_at']