Django REST Polymorphic

0.1.10 · active · verified Sun Apr 12

django-rest-polymorphic is a Python library that provides polymorphic serializers for Django REST Framework. It enables you to easily define serializers for models that utilize inheritance through the django-polymorphic library. The current version is 0.1.10, and while its core functionality has been integrated into django-polymorphic, the standalone package is still available on PyPI.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up polymorphic models using `django-polymorphic`, define individual `ModelSerializer`s for each concrete type, and then create a `PolymorphicSerializer` to handle the mapping. Finally, it shows how to integrate this into a Django REST Framework `ViewSet` to expose a polymorphic API endpoint. You would then include this ViewSet in your Django project's `urls.py`.

from django.db import models
from rest_framework import serializers, viewsets
from polymorphic.models import PolymorphicModel
from rest_polymorphic.serializers import PolymorphicSerializer

# 1. Define polymorphic models using django-polymorphic
class Project(PolymorphicModel):
    topic = models.CharField(max_length=30)

class ArtProject(Project):
    artist = models.CharField(max_length=30)

class ResearchProject(Project):
    supervisor = models.CharField(max_length=30)

# 2. Define serializers for each concrete model
class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('topic', 'resource_type') # 'resource_type' is added automatically by PolymorphicSerializer

class ArtProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArtProject
        fields = ('topic', 'artist', 'resource_type')

class ResearchProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResearchProject
        fields = ('topic', 'supervisor', 'resource_type')

# 3. Create a PolymorphicSerializer to map models to serializers
class ProjectPolymorphicSerializer(PolymorphicSerializer):
    model_serializer_mapping = {
        Project: ProjectSerializer,
        ArtProject: ArtProjectSerializer,
        ResearchProject: ResearchProjectSerializer
    }

# 4. Use the polymorphic serializer in a ViewSet
class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectPolymorphicSerializer

view raw JSON →