pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

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?


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