我有3个表(其中2个表使用ForeignKey属于1个表)。
我可以跨3个表创建queryset。但是,我无法从序列化的返回数据中获取命名表信息,如下所示。
谁能告诉我如何修改序列化程序?
class lightData(generics.ListAPIView):
serializer_class = lightSerializer
pagination_class = None
def get_queryset(self):
certificate = self.kwargs['certificate']
return Light.objects.prefetch_related('zone__namingzone')
models.py
class Zone(models.Model):
zone=models.CharField(max_length=20)
conditioned=models.BooleanField(default=True)
def __str__(self):
return self.zone
class Light(models.Model):
zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone')
lpd=models.IntegerField()
sensor=models.BooleanField(default=True)
class Meta:
unique_together = (('certificate', 'zone'),)
def __str__(self):
return str(self.certificate)+"_"+str(self.zone)
class Naming(models.Model):
zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone')
naming=models.CharField(max_length=20)
def __str__(self):
return str(self.zone)+"_"+self.naming
serializer.py
from rest_framework import serializers
from .models import Certificate,Zone,Light,OA,Naming
class zoneSerializer(serializers.ModelSerializer):
class Meta:
model=Zone
fields = ('zone','conditioned')
class lightSerializer(serializers.ModelSerializer):
zone = zoneSerializer()
class Meta:
model=Light
fields = ('zone','lpd','sensor')
class namingSerializer(serializers.ModelSerializer):
zone=zoneSerializer()
class Meta:
model=Naming
fields=('zone','naming')
答案 0 :(得分:3)
创建一个新的序列化程序 NamingNewSerializer
并将其添加到您的 zoneSerializer
内,如下所示,
class NamingNewSerializer(serializers.ModelSerializer):
class Meta:
model = Naming
fields = '__all__'
class zoneSerializer(serializers.ModelSerializer):
namingzone = NamingNewSerializer(many=True)
class Meta:
model = Zone
fields = ('zone', 'conditioned', 'namingzone')
此处 namingzone
是 反向关系关键字 ,用于获取/获取 {{1} } 实例中的一个 Naming
实例。
除此之外,我建议您在命名课程时遵循CapWords convention:)