Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Serializer for Django Rest Framework

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

season
  |
evening
  |
event

Any suggestions how to achieve this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading