Home > Mobile >  drf - how to access field of parent serializer in child serializer
drf - how to access field of parent serializer in child serializer

Time:02-24

I have 3 models
models.py

class First(models.Model):
    is_available = models.BooleanField(default=False)
    
class Second(models.Model):
    some_field = models.BooleanField(default=False)
   
class Third(models.Model):
    first = models.ForeignKey(First, null=True, blank=True, on_delete=models.CASCADE)
    second = models.ForeignKey(Second, null=True, blank=True, on_delete=models.CASCADE)

serializers.py

class SecondSerializer(serializers.Serializer):
    some_field = serializers.BooleanField()
    is_available = serializers.BooleanField() # field from models.First    

class ThirdSerializer(serializers.Serializer):
    second = SecondSerializer()

views.py

class ThirdViewSet(mixins.ListModelMixin, GenericViewSet):
    .........
    def get_queryset(self):
        return Third.objects.select_related('first', 'second')

I have to send the response through ThirdSerializer but First.is_available should be sent in SecondSerializer. How can I achieve that?

CodePudding user response:

You can try adding a property is_available to second object and pass it to serializer.

class SecondSerializer(serializers.Serializer):
    some_field = serializers.BooleanField()
    is_available = serializers.BooleanField()

class ThirdSerializer(serializers.Serializer):
    second = serializers.SerializerMethodField()

    def get_second(self, obj):
        second = obj.second
        second.is_available = obj.first.is_available
        return SecondSerializer(instance=second).data
  • Related