我有 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错误
.
categories
categories.name
TypeError
TypeError: Cannot read property 'name' of undefined
这是我的serializers
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']
要将类别名称包含在Post数据中,您可以修改PostSerializer以使用类别的嵌套序列化程序,而不是仅显示其 ID。这样,PostSerializer将包含CategorySerializer每个相关类别的 ,让您可以访问类别名称。
Post
PostSerializer
CategorySerializer
具体操作如下:
CategorySerializer``categories
在 中PostSerializer,设置为categories使用。这将允许每个帖子包含有关其类别的详细信息。CategorySerializer``many=True
CategorySerializer``many=True
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) categories = CategorySerializer(many=True) # Use CategorySerializer for detailed info class Meta: model = Post fields = ['id', 'title', 'body', 'owner', 'comments', 'categories', 'created_at']
经过此更改后,每个帖子的 JSON 响应应如下所示:
{ "id": 4, "title": "BLOG PAGE", "body": "testing", "owner": "ankit", "comments": [], "categories": [ { "id": 2, "name": "Python", "owner": "ankit", "posts": [4, 5, 6, 8] } ], "created_at": "2021-05-07T17:22:32.989706Z" }
现在,每个类别对象将包含id、、和字段name,允许您直接在前端访问。owner``posts``category.name
id
name
owner``posts``category.name
在您的 React 组件中,您现在可以通过迭代来显示类别名称this.state.data.categories:
this.state.data.categories
render() { const { data, loaded, placeholder } = this.state; if (!loaded) { return <p>{placeholder}</p>; } return ( <> <h1 className="main-title">{data.title}</h1> <div className="container"> <div className="box1"> <h2>Categories</h2> <div className="categories"> {data.categories.map(category => ( <span key={category.id}>{category.name}</span> ))} </div> </div> </div> </> ); }
.map
categories``data
这种方法避免TypeError了让您直接访问name属性。