Hannan
Hannan

Reputation: 1191

Django Rest Framework: How to get value of the ForeignKey

In Django Rest Framework, how can I get the value of the ForeignKey instead of 'id'? I want to get financial_year as full year i.e. 2012 or 2013 and not the the id of e.g. 1 and 2 in the output. How can I achieve that?

The output I'm getting is following:

[{"financial_year":1,"mainline_revenue":18743.0,"regional_revenue":2914.0},{"financial_year":2,"mainline_revenue":23876.0,"regional_revenue":3204.0}]

But I want:

[{"financial_year":2012,"mainline_revenue":18743.0,"regional_revenue":2914.0},{"financial_year":2013,"mainline_revenue":23876.0,"regional_revenue":3204.0}]

Models.py:

class FinancialData(models.Model):
    financial_year = models.ForeignKey(Year)
    mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2)
    regional_revenue = models.DecimalField(max_digits=7, decimal_places=2)

class Year(models.Model):
    YEARS_CHOICE = (
        (2012, 2012),
        (2013, 2013),
        (2014, 2014),
        (2015, 2015),
        (2016, 2016),
        )
    year = models.IntegerField(choices=YEARS_CHOICE, blank=True, null=True)

Serializers.py:

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

Upvotes: 1

Views: 75

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9921

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.

Upvotes: 2

Related Questions