Created
January 6, 2020 02:20
-
-
Save panw3i/447a0208b7ed641ee50127596ae4c44e to your computer and use it in GitHub Desktop.
SerializerMethodField 序列化指定字段,该字段可不在模型类中
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class DeviceSerializer(serializers.ModelSerializer): | |
| """ | |
| 设备序列化 | |
| """ | |
| cabinet = serializers.SerializerMethodField() | |
| def get_cabinet(self, obj): | |
| cabinets = Cabinet.objects.filter(id=obj.cabinet_id) | |
| if cabinets is not None and len(cabinets) > 0: | |
| return CabinetSerializer(cabinets[0]).data | |
| else: | |
| return "" | |
| class Meta: | |
| model = Device | |
| fields = ('id', 'device_name', 'device_type', 'brand', 'model', | |
| 'hardware', 'cabinet_id', 'cabinet', 'created_time', 'modified_time' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment