django 如何在DRF中“扁平化”嵌套串行器?

7d7tgy0s  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(118)

我们有一个嵌套的序列化器,我们想“扁平化”。但我没有太多的运气找到如何在文档中实现这一点。
这是电流输出。

{
    "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2",
    "quantity": 1,
    "player": {
        "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8",
        "game": "MLB The Show 22",
        "name": "Jesus Tinoco",
        "all_positions": [
            "CP"
        ]
    }
}

这是我想要的:

{
    "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2",
    "quantity": 1,
    "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8",
    "game": "MLB The Show 22",
    "name": "Jesus Tinoco",
    "all_positions": [
        "CP"
    ]
}

下面是序列化器的设置:

class PlayerProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlayerProfile
        fields = (
            'card_id',
            'game',
            'name',
            'all_positions',
        )

class UserInventoryItemSerializer(serializers.ModelSerializer):
    player = PlayerProfileSerializer()
    class Meta:
        model = UserInventoryItem
        fields = (
            'user_inventory',
            'quantity',
            'player',
        )

以下是该视图:

class OwnedInventoryView(viewsets.ModelViewSet):
    serializer_class = UserInventoryItemSerializer
    filterset_class = UserInventoryItemFilter

    def get_queryset(self):
        order_by = self.request.query_params.get('order_by', '')

        if order_by:
            order_by_name = order_by.split(' ')[1]
            order_by_sign = order_by.split(' ')[0]
            order_by_sign = '' if order_by_sign == 'asc' else '-'
            return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk']).order_by(order_by_sign + order_by_name)

        return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk'])
bbuxkriu

bbuxkriu1#

您可以使用.to_representation()方法更改数据结构:

class UserInventoryItemSerializer(serializers.ModelSerializer):
    player = PlayerProfileSerializer()

    class Meta:
        model = UserInventoryItem
        fields = (
            'user_inventory',
            'quantity',
            'player',
        )

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        player = representation.pop('player')
        
        for key, value in player.items():
            representation[key] = value

        return representation

相关问题