[Answered ]-Django Rest Framework: How to get value of the ForeignKey

2👍

You can access foreign key fields value by specifying the fields explicitly

class FinancialDataSerializer(serializers.ModelSerializer):
    financial_year = serializers.CharField(source='financial_year.year')
    class Meta:
        model = FinancialData
        fields = (
            'financial_year',
            'mainline_revenue',
            'regional_revenue',)

source parameter defines the attribute name. Lets say if your Year model has a field name year then it would work. If the field name is different then you have to change it.

Leave a comment