Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get attribute of a foreign key inside serializer in Django REST framework?

I have two models named Market, Exchange

class Exchange(models.Model):
    name = models.CharField(max_length=20)


class Market(models.Model):
    exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE)
    price = models.FloatField(default=0.0)

What I need to do is get name field in Exchange Model inside MarketSerializer ->

class MarketSerializer(serializers.ModelSerializer):
    class Meta:
        model = Market
        fields = ('exchange_name', 'price', )

How can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can archive those things using SerializerMethodField() like this

class MarketSerializer(serializers.ModelSerializer):
    exchange_name = serializers.SerializerMethodField()

    class Meta:
        model = Market
        fields = ('exchange_name', 'price', )

    def get_exchange_name(self, obj):
        return obj.exchange.name 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading