如何从Django API访问Reaction中的伪造键值 [英] How to access forgin key value in react from django api

查看:21
本文介绍了如何从Django API访问Reaction中的伪造键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Django API,其中我有帖子模型,该模型通过伪造键链接到评论和类别表。现在,我正在搜索帖子详细信息数据,当我尝试访问帖子的类别时,它返回sid,我想访问类别的名称,这是我的帖子列表视图

{
        "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']

推荐答案

我尝试访问帖子类别,它返回ID,我想访问类别名称这是我的帖子列表视图

1.仅获取类别名称。

您可以使用SlugRelatedField

按如下方式修改您的PostSerializer

class PostSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    categories = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')

    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": [
            "Python"
        ],
        "created_at": "2021-05-07T17:22:32.989706Z"
    },

2.要嵌套完整的Category对象

class PostSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    categories = CategorySerializer(many=True)

    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"
}

这篇关于如何从Django API访问Reaction中的伪造键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆