[Django]-How to include a field from the joining table in the queryset?

4👍

You’re going to want to use a nested relation like this:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

Source: http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

So for your situation it would be:

class PinnedSerializer(ModelSerializer):
    class Meta:
        model = Pinned
        fields = ('type', 'country_id')

class UserSerializer(ModelSerializer):
    pins = PinnedSerializer(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'countries', 'pins')

Newest version tested with actual project:

class PinnedSerializer(serializers.ModelSerializer):
    country_id = serializers.ReadOnlyField(source='country.id')
    class Meta:
        model = Pinned
        fields = ('type', 'country_id')


class UserSerializer(serializers.ModelSerializer):
    pinned_set = PinnedSerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'pinned_set')

Output:

{
    "id": 3,
    "username": "bobdole",
    "pinned_set": [
        {
            "type": 1,
            "country_id": 250
        }
    ]
}

Leave a comment