从1:M相关模型DRF查询对象

时间:2019-01-24 10:22:40

标签: django django-models django-rest-framework

设计了一个具有多级1:M关系的Django模型,能够获得用DRF编写Serializers的json响应。执行CRUD操作看起来很容易,但仅特定于该表,我期望响应类似于下面的响应,然后遇到一个称为嵌套序列化器的术语,因为我对此不太了解,有人可以建议我为以下型号提供一个

{
  "Blocks": [
    {
      "id": 1,
      "name": "A",
      "Floor": [
        {
          "id": 1,
          "name": 0,
          "count":2,
          "books": [
            {
              "id": 1,
              "name": "White Tiger"
            },
            {
              "id": 1,
              "name": "The Alchemist"
            }
          ]
        },
        {
          "id": 2,
          "name": 1,
          "count": 2,
          "books": [
            {
              "id": 1,
              "name": "Facebook"
            },
            {
              "id": 1,
              "name": "The Master Blaster"
            }
          ]
        }
      ]
    },
    {
      "id": "2",
      "name": "B",
      "Floor": [
        {
          "id": 1,
          "name": 0,
          "count":2,
          "books": [
            {
              "id": 1,
              "name": "Know Your self"
            },
            {
              "id": 1,
              "name": "The Naga"
            }
          ]
        },
        {
          "id": 2,
          "name": 1,
          "count":2,
          "books": [
            {
              "id": 1,
              "name": "The Data Analyics"
            },
            {
              "id": 1,
              "name": "Become Master of R"
            }
          ]
        }
      ]
    }
  ]
}

每添加或删除一本书,它都应反映在楼层的 count 属性中

1 个答案:

答案 0 :(得分:0)

根据the documentation,对于只读,类似这样的方法应该起作用:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book

class FloorSerializer(serializers.ModelSerializer):
    book = BookSerializer(many=True, read_only=True)

    class Meta:
        model = Floor

class BlockSerializer(serializers.ModelSerializer):
    Floor = FloorSerializer(many=True, read_only=True)

    class Meta:
        model = Block

For writing/updating,将创建和/或更新方法写入BlockSerializer。

class BlockSerializer(serializers.ModelSerializer):
    Floor = FloorSerializer(many=True)

    class Meta:
        model = Block

    def create(self, validated_data):
        floors_data = validated_data.pop('Floors')
        block = Blocks.objects.create(**validated_data)
        for floor_data in floors_data:
            books_data = floor_data.pop('books')
            floor = Floor.objects.create(block=block, **floor_data)
            for book_data in books_data:
                Book.objects.create(floor=floor, **book_data)

希望这会有所帮助