I have 3 tables(2 tables are belonging to 1 table using ForeignKey).
I could create queryset across 3 tables. However, I cannot get naming table information from serialized return data as below.
Could anyone tell me how I should revise serializer?
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')
Create a new serializer,
NamingNewSerializer
and add it inside yourzoneSerializer
as below,here the
namingzone
is the reverse relation keyword which is used to fetch/getNaming
instances from a singleZone
instance.Apart from that, I suggest you to follow the CapWords convention while name your classes :)