Skip to main content

Polymorphic serializers for Django REST Framework.

Project description

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"

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-rest-polymorphic-0.1.8.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

django_rest_polymorphic-0.1.8-py2.py3-none-any.whl (5.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file django-rest-polymorphic-0.1.8.tar.gz.

File metadata

  • Download URL: django-rest-polymorphic-0.1.8.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.9.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.7.0

File hashes

Hashes for django-rest-polymorphic-0.1.8.tar.gz
Algorithm Hash digest
SHA256 8a763ab0459b93724d186e101c3b92d0b1916305b6b221f65064c02ebc2267a8
MD5 ed285fb8d6e3a084caf092f00e60d30f
BLAKE2b-256 d8d960a36f52822614271f3d6fc849306963a00985f19eb95be6239cffcf03a3

See more details on using hashes here.

Provenance

File details

Details for the file django_rest_polymorphic-0.1.8-py2.py3-none-any.whl.

File metadata

  • Download URL: django_rest_polymorphic-0.1.8-py2.py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.9.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.7.0

File hashes

Hashes for django_rest_polymorphic-0.1.8-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 a29a0a7a0fd804e7a9b0b86025591aa4ab23d4c450dd2b7a088c5976ac9283a1
MD5 b3444aace536217d49dcc951c1aeec32
BLAKE2b-256 0e77b2eef0c31c8c623ef73fcf6cd3c1c7f22d7ee9bbbb0c6ba36ca5a3c9f07a

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page