How I can serialize information across 3 tables in

2019-08-11 13:27发布

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?

enter image description here views.py

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')

1条回答
欢心
2楼-- · 2019-08-11 14:29

Create a new serializer, NamingNewSerializer and add it inside your zoneSerializer as below,

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')

here the namingzone is the reverse relation keyword which is used to fetch/get Naming instances from a single Zone instance.


Apart from that, I suggest you to follow the CapWords convention while name your classes :)

查看更多
登录 后发表回答