如何从 django api 访问 forgin 键值

IT技术 reactjs django django-models django-rest-framework
2021-05-10 04:48:16

我有 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 我认为我可以通过将其放在例如.前面来访问它categoriescategories.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']
1个回答

我尝试访问该帖子的类别,它返回 s 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"
}