查询1:M相关模型DRF中的对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查询1:M相关模型DRF中的对象相关的知识,希望对你有一定的参考价值。
设计了一个具有多级1:M关系的Django模型,能够获得在DRF中编写序列化器的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"
}
]
}
]
}
]
}
每当添加/删除书籍时,它都应反映在楼层的计数属性中
答案
根据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,将创建和/或更新-methods写入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)
希望这可以帮助
以上是关于查询1:M相关模型DRF中的对象的主要内容,如果未能解决你的问题,请参考以下文章