Skip to main content
https://travis-ci.org/apirobot/django-rest-polymorphic.svg?branch=master https://codecov.io/gh/apirobot/django-rest-polymorphic/branch/master/graph/badge.svg https://badge.fury.io/py/django-rest-polymorphic.svg

Django REST Polymorphic

Polymorphic serializers for Django REST Framework.

Overview

django-rest-polymorphic allows you to easily define serializers for your inherited models that you have created using django-polymorphic library.

Installation

Install using pip:

$ pip install django-rest-polymorphic

Usage

Define your polymorphic models:

# models.py
from django.db import models
from polymorphic.models import PolymorphicModel


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)

Define serializers for each polymorphic model the way you did it when you used django-rest-framework:

# serializers.py
from rest_framework import serializers
from .models import Project, ArtProject, ResearchProject


class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('topic', )


class ArtProjectSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ArtProject
        fields = ('topic', 'artist', 'url')
        extra_kwargs = {
            'url': {'view_name': 'project-detail', 'lookup_field': 'pk'},
        }


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

Note that if you extend HyperlinkedModelSerializer instead of ModelSerializer you need to define extra_kwargs to direct the URL to the appropriate view for your polymorphic serializer.

Then you have to create a polymorphic serializer that serves as a mapper between models and serializers which you have defined above:

# serializers.py
from rest_polymorphic.serializers import PolymorphicSerializer


class ProjectPolymorphicSerializer(PolymorphicSerializer):
    model_serializer_mapping = {
        Project: ProjectSerializer,
        ArtProject: ArtProjectSerializer,
        ResearchProject: ResearchProjectSerializer
    }

Create viewset with serializer_class equals to your polymorphic serializer:

# views.py
from rest_framework import viewsets
from .models import Project
from .serializers import ProjectPolymorphicSerializer


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectPolymorphicSerializer

Test it:

$ http GET "http://localhost:8000/projects/"
HTTP/1.0 200 OK
Content-Length: 227
Content-Type: application/json

[
    {
        "resourcetype": "Project",
        "topic": "John's gathering"
    },
    {
        "artist": "T. Turner",
        "resourcetype": "ArtProject",
        "topic": "Sculpting with Tim",
        "url": "http://localhost:8000/projects/2/"
    },
    {
        "resourcetype": "ResearchProject",
        "supervisor": "Dr. Winter",
        "topic": "Swallow Aerodynamics"
    }
]
$ http POST "http://localhost:8000/projects/" resourcetype="ArtProject" topic="Guernica" artist="Picasso"
HTTP/1.0 201 Created
Content-Length: 67
Content-Type: application/json

{
    "artist": "Picasso",
    "resourcetype": "ArtProject",
    "topic": "Guernica",
    "url": "http://localhost:8000/projects/4/"
}

Customize resource type

As you can see from the example above, in order to specify the type of your polymorphic model, you need to send a request with resource type field. The value of resource type should be the name of the model.

If you want to change the resource type field name from resourcetype to something else, you should override resource_type_field_name attribute:

class ProjectPolymorphicSerializer(PolymorphicSerializer):
    resource_type_field_name = 'projecttype'
    ...

If you want to change the behavior of resource type, you should override to_resource_type method:

class ProjectPolymorphicSerializer(PolymorphicSerializer):
    ...

    def to_resource_type(self, model_or_instance):
        return model_or_instance._meta.object_name.lower()

Now, the request for creating new object will look like this:

$ http POST "http://localhost:8000/projects/" projecttype="artproject" topic="Guernica" artist="Picasso"

Metadata

Release files for django-rest-polymorphic 0.1.10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-rest-polymorphic 0.1.10
File Size Uploaded
django-rest-polymorphic-0.1.10.tar.gz 6.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-rest-polymorphic 0.1.10
File Interpreter ABI Platform
django_rest_polymorphic-0.1.10-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 12.5 kB

Release files / django-rest-polymorphic-0.1.10.tar.gz

Download URL django-rest-polymorphic-0.1.10.tar.gz
Size 6.5 kB
Tags Source
SHA-256 checksum
How to use checksums
2960f58ed9a8bb0d42bc72c8ffaadfbd7f37d2573d42a1cd9a6460f3d572b519
BLAKE2b-256 checksum
How to use checksums
f486285f7da71ecd82ce6f1765ffb74425faf8244d8554cb6d00542286157701
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.8.3 requests/2.28.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.64.0 CPython/3.8.10

Release files / django_rest_polymorphic-0.1.10-py2.py3-none-any.whl

Download URL django_rest_polymorphic-0.1.10-py2.py3-none-any.whl
Size 6.0 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
f3980e3e2af73357e7913f9b1410ef856866bcfcc46903b70fe9621118bb538c
BLAKE2b-256 checksum
How to use checksums
d390e20bde06ea67111718ad8d03e21cccdfe37e24ccdff30ea22100a3004070
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.8.3 requests/2.28.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.64.0 CPython/3.8.10

Release history Release notifications | RSS feed

This release

0.1.10 This release

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page