Django REST框架深度仅适用于指定字段

2024-06-28 20:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个Django REST框架序列化程序。现在,我为我的博客文章添加了一个序列化程序,但我只希望序列化程序深度用于指定的字段。直到现在我才明白:

{
  "results": [
      {
          "postid": 1,
          "title": "Test Title",
          "slug": "test-title",
          "description": "Test Description",
          "tag": {
              "tagid": 1,
              "tagname": "school"
          },
          "views": 15,
          "release_date": "2021-05-25T17:15:22.223311Z",
          "user": {
              "userid": 1,
              "password": "pbkdf2_sha256$216000$drVQlm6CdO+g90ygM3gXFUHBb+ctaKDA=",
              "username": "user1",
              "email": "testemail@gmail.com",
              "posts": 0,
              "date_joined": "2021-05-25T17:13:29.865119Z",
              "last_login": "2021-05-25T17:14:12.808671Z",
              "is_admin": true,
              "is_active": true,
              "is_staff": true,
              "is_superuser": true
          },
          "city": "New York",
          "country": {
              "countryid": 1,
              "continent": "america",
              "countryname": "usa",
              "currency": "$",
              "symbol": "US"
          }
      },
      ...
    ]
}

这是我的序列化程序:

class BlogPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Job
        fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"]
        depth = 1

但问题是,我只想要标签和国家的深度,而不是用户:/

{
  "results": [
      {
          "postid": 1,
          "title": "Test Title",
          "slug": "test-title",
          "description": "Test Description",
          "tag": {
              "tagid": 1,
              "tagname": "school"
          },
          "views": 15,
          "release_date": "2021-05-25T17:15:22.223311Z",
          "user": 1,
          "city": "New York",
          "country": {
              "countryid": 1,
              "continent": "america",
              "countryname": "usa",
              "currency": "$",
              "symbol": "US"
          }
      },
      ...
    ]
}

你有过同样的问题吗?谢谢你的帮助:)


Tags: test程序truecitydaterelease序列化title
1条回答
网友
1楼 · 发布于 2024-06-28 20:58:48

假设您还有标记和国家的序列化程序:

class BlogPostSerializer(serializers.ModelSerializer):
    tag = TagSerializer(read_only=True)
    country = CountrySerializer(read_only=True)

    class Meta:
        model = Job
        fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"]

相关问题 更多 >