假设我有这样的模型:
class Device(models.Model):
name = models.CharField(max_length=100,null=True)
model = models.CharField(max_length=100,null=True)
lab = models.ForeignKey(Lab,null=True, related_name='devices')
class Lab(models.Model):
name = models.CharField(max_length=100)
实验室可以有多个设备。 当我创建序列化器时,我能够得到这样的东西:
{'name':'My Lab','devices':[{'name':'Device 1','model':'iPhone'},{'name':'Device 2','model':'iPad'}]}
但是,我想要取回的是键/值对而不是设备列表,如下所示:
{'name':'My Lab','devices':{'Device 1':{'model':'iPhone'},'Device 2':{'model':'iPad'}}}
我想我必须使用SerializerMethodField
来完成这项工作,但我无法搞清楚。
答案 0 :(得分:1)
这就是我提出的:
class LabSerializer(serializers.ModelSerializer):
devices = serializers.SerializerMethodField()
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Lab
fields = ('name','devices')
def get_devices(self, obj):
devices = {}
for d in Device.objects.filter(lab = obj):
serializer = DeviceSerializer(d)
devices[d.name] = serializer.data
return devices