Home > Back-end >  How to get a relation from a relation in a serializer?
How to get a relation from a relation in a serializer?

Time:05-26

I have 3 models:

class Artist(Timestamps):
    name = models.CharField('Name', max_length=255, blank=True)
    ...

class Festival(Timestamps):
    name = models.CharField(max_length=255, blank=True)
    ...

class Event(Timestamps):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=True)
    festival = models.ForeignKey(Festival, on_delete=models.CASCADE, null=True)

Now I wan't all the id's from the festivals an artist is playing. I have a serializer like this:

class ArtistFestivalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Artist
        fields = ('id', 'name', 'event_set')

But this only gives me the id's of the event. Any ideas how to get trough the Event to the Festival?

Thanks in advance

EDIT - the view is:

class FestivalArtists(generics.ListAPIView):
    serializer_class = ArtistFestivalSerializer
    def get_queryset(self):
        queryset = Artist.objects.prefetch_related('event_set').filter(event__isnull=False).distinct().order_by('name')
        return queryset

CodePudding user response:

I think you need to add the custom field for that.

class ArtistFestivalSerializer(serializers.ModelSerializer):
    festival_ids = serializers.SerializerMethodField(read_only = True)

    class Meta:
        model = Artist
        fields = ('id', 'name', 'event_set', 'festival_ids')

    def get_festival_ids(self, obj):
        return list(Event.objects.filter(artist = obj).values_list('festival_id').distinct())
  • Related