Home > Back-end >  Custom Serializer for Django Rest Framework
Custom Serializer for Django Rest Framework

Time:11-09

I'm searching for a solution to create a serializer / API Endpoint to represent data in a custom order. When adding serializers and viewsets to DRF, I only get the fields associated with that Model. But what I like to have is a custom structure of all my models together. As an example:

I have a model called season, a model called evenings and a model called events. Now I'd like to have an API Endpoint to have that all together, like so:

{
  "requestTime": "2021-11-09 08:20",
  "requestURL": "/all",
  "requestMethod": "GET",
  "responseCode": 200,
  "season": "2021/2022",
  "evenings": [
        {
          "evevning_id": 0,
          "day": "",
          "date": "2021-11-11",
          "event_count": 2,
          "events": [
            {},
            {}
          ]
        }
      ]
}

For data structure in the models I have some ForeignKeys like:

season
  |
evening
  |
event

Any suggestions how to achieve this?

CodePudding user response:

Use nested serializer (Season > Evening > Event) like this.

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Event
        fields = ['id',...]


class EveningSerializer(serializers.ModelSerializer):
    events = EventSerializer(many=True)
    class Meta:
        model = models.Evening
        fields = ['id', 'day', 'date','events',...]


class SeasonSerializer(serializers.ModelSerializer):
    evenings = EveningSerializer(many=True)
    class Meta:
        model = models.Season
        fields = ['id', 'season', 'evenings',...]

make sure when fetching season from database, use prefetch related in queryset.

  • Related