我对drf有问题。我有设备序列化器:
from rest_framework import serializers
from smarthome.models import Device
class DeviceSerializer(serializers.Serializer):
id = serializers.ReadOnlyField()
name = serializers.CharField(max_length=80)
address = serializers.CharField(max_length=17)
def create(self, validated_data):
return Device.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.address = validated_data.get('address', instance.address)
instance.save()
return instance
另外,我有结果序列化器:
from rest_framework import serializers
from smarthome.models import Result
from smarthome.models import Device
class ResultSerializer(serializers.Serializer):
temperature = serializers.CharField(max_length=80)
moisture = serializers.CharField(max_length=80)
light = serializers.CharField(max_length=80)
conductivity = serializers.CharField(max_length=80)
battery = serializers.CharField(max_length=80)
date = serializers.ReadOnlyField()
device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all())
def create(self, validated_data):
print(validated_data)
return Result.objects.create(**validated_data)
我不知道如何将设备结果添加到设备串行器。我也想有可能使用来自用户的限制发送来限制响应结果的数量。
有我的模特:
class Device(models.Model):
name = models.CharField(max_length=80)
address = models.CharField(max_length=17)
class Result(models.Model):
temperature = models.CharField(max_length=80)
moisture = models.CharField(max_length=80)
light = models.CharField(max_length=80)
conductivity = models.CharField(max_length=80)
battery = models.CharField(max_length=80)
date = models.DateTimeField(auto_now_add=True)
device = models.ForeignKey('Device', related_name='statuses', on_delete=models.CASCADE)
现在,作为回应,我得到了:
{ “ id”:1 “ name”:“名称”, “ address”:“ c4:7c:8d:6a:fb:27” }
我想要这样的东西:
{ “ id”:1 “ name”:“名称”, “ address”:“ c4:7c:8d:6a:fb:27”, “结果”:{ { “温度”:“ 21.5”, “水分”:“ 61”, ... }, { ... } } }
答案 0 :(得分:0)
由于用例非常琐碎,因此应使用ModelSerializer来代替Serializer
类来声明序列化程序,这样可以节省代码并为您管理很多事情。
from rest_framework import serializers
from smarthome.models import Result
from smarthome.models import Device
class ResultSerializer(serializers.ModelSerializer):
class Meta:
model = Result
fields = ('id', 'temperature', 'moisture', 'light', 'conductivity', 'battery', 'date')
class DeviceSerializer(serializers.ModelSerializer):
results = ResultSerializer(many=True, source='result_set')
class Meta:
model = Device
fields = ('id', 'name', 'address', 'results')
现在,使用DeviceSerializer
反序列化Device
模型的实例时,您将获得预期的输出。
{“ id”:1,“ name”:“名称”,“ address”:“ c4:7c:8d:6a:fb:27”,“ results”:{{“ temperature”:“ 21.5”, “ moisture”:“ 61”,...},{...}}}
答案 1 :(得分:0)
您可以在这方面使用嵌套的序列化器。 请参阅Nested relationships的官方文档。