Skip to content

Instantly share code, notes, and snippets.

@panw3i
Created January 6, 2020 02:20
Show Gist options
  • Select an option

  • Save panw3i/447a0208b7ed641ee50127596ae4c44e to your computer and use it in GitHub Desktop.

Select an option

Save panw3i/447a0208b7ed641ee50127596ae4c44e to your computer and use it in GitHub Desktop.
SerializerMethodField 序列化指定字段,该字段可不在模型类中
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