Django Rest Framework - Get related model field in serializer

35,164

Solution 1

Simple as that, adding the WineSerializer as a field solved it.

class BottleSerializer(serializers.HyperlinkedModelSerializer):
    wine = WineSerializer(source='wine')

    class Meta:
        model = Bottle
        fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more')

with:

class WineSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Wine
        fields = ('id', 'url', 'color', 'country', 'region', 'appellation')

Thanks for the help @mariodev :)

Solution 2

If you want to get specific field you can use Serializer Fields

https://www.django-rest-framework.org/api-guide/fields/

    class BottleSerializer(serializers.HyperlinkedModelSerializer):
        winecolor = serializers.CharField(read_only=True, source="wine.color")

        class Meta:
            model = Bottle
            fields = ('url', 'winecolor', 'user', 'date_rated', 'rating', 'comment', 'get_more')
Share:
35,164
bpipat
Author by

bpipat

CTO @ Seelk, Tech/music enthusiast, Python/Django addict

Updated on July 09, 2022

Comments

  • bpipat
    bpipat almost 2 years

    I'm trying to return a HttpResponse from Django Rest Framework including data from 2 linked models. The models are:

    class Wine(models.Model):
    
        color = models.CharField(max_length=100, blank=True)
        country = models.CharField(max_length=100, blank=True)
        region = models.CharField(max_length=100, blank=True)
        appellation = models.CharField(max_length=100, blank=True)
    
    class Bottle(models.Model):
    
        wine = models.ForeignKey(Wine, null=False)
        user = models.ForeignKey(User, null=False, related_name='bottles')
    

    I'd like to have a serializer for the Bottle model which includes information from the related Wine.

    I tried:

    class BottleSerializer(serializers.HyperlinkedModelSerializer):
        wine = serializers.RelatedField(source='wine')
    
        class Meta:
            model = Bottle
            fields = ('url', 'wine.color', 'wine.country', 'user', 'date_rated', 'rating', 'comment', 'get_more')
    

    which doesn't work.

    Any ideas how I could do that?

    Thanks :)

  • mariodev
    mariodev over 10 years
    Glad you sort that out. Can you also please explain what WineSerializer class stands for, so we have a clear answer..
  • arturataide
    arturataide over 8 years
    I've done this but I'm getting the fallowing error HyperlinkedRelatedField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.`. What am I doing wrong?
  • Mahabubur Rahaman Melon
    Mahabubur Rahaman Melon almost 8 years
    got error like this: AssertionError(u"HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.",) is not JSON serializable.
  • shanemgrey
    shanemgrey over 7 years
    You shouldn't need the source='wine' argument since it's the same as the name. In fact I'm surprised if you aren't getting a runtime error for that. Instead you can add other args like (many=False, read_only=True)
  • roboslone
    roboslone over 7 years
    To anybody with the same problem - you don't have to use HyperlinkedModelSerializer, ModelSerializer will do just fine.
  • mgalgs
    mgalgs almost 7 years
    This will result in an embedded object under the wine property. Is there a way to get specific fields from the related Wine model embedded directly in the top-level object?
  • Rishi Latchmepersad
    Rishi Latchmepersad about 3 years
    For anyone else who spent way too long trying to figure out how this links to the related serializer, the source="wine.color" follows the foreign key relationship defined in the model. In this case, the foreign key was named 'wine', and the related field is 'color'.