首页 > 解决方案 > Django REST Framework 深度仅适用于指定字段

问题描述

所以我有一个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"
          }
      },
      ...
    ]
}

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

标签: pythondjangodjango-rest-framework

解决方案


假设您还有标签和国家/地区的序列化程序:

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

推荐阅读