简体   繁体   中英

Django rest framework access related custom fields

I want to sum all the Bars progress value in the FooSerializer

The code order is FooSerializer.get_progress -> BarSerializer , I can't access BarSerializer.progess in FooSerializer .

from django.db import models
from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet


class Foo(models.Model):
    name = models.CharField(max_length=180)

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name='bars', on_delete=models.CASCADE)


class BarSerializer(serializers.ModelSerializer):
    progress = serializers.SerializerMethodField()

    def get_progress(self, instance):
        return 100  # some computed value


class FooSerializer(serializers.ModelSerializer):
    bars = BarSerializer(many=True)
    progress = serializers.SerializerMethodField()

    def get_progress(self, instance):
        # how to access barSerializer's progress ?
        total = sum(x.progress for x in instance.bars)
        return total

Instead of definining progress in bar serializer you can set the same method as a property in Bar model .

class Bar(models.Model):
    foo = models.ForeignKey(Foo,related_name='bars',on_delete=models.CASCADE)

    @property
    def progress(self):
        return 100

you can specify the progress field in Barserializer's fields.

class BarSerializer(serializers.ModelSerializer):
     class Meta:
           model = Bar 
           fields = '__all__' #specify fields you need in list/tuple(progress will be included in fields).
        

While for Foo serializer you can don't need the progress serializer field

class FooSerializer(serializers.ModelSerializer):
    bars = BarSerializer(many=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM