Git Product home page Git Product logo

django-rest-marshmallow's Introduction


Marshmallow schemas for Django REST framework.


Overview

django-rest-marshmallow provides an alternative serializer implementation to the built-in serializers, by using the python marshmallow library, but exposing the same API as REST framework's Serializer class.

Requirements

  • Python (3.6+)
  • Django REST framework (3.8+)
  • Marshmallow (3.0.0+)

Installation

Install using pip...

$ pip install django-rest-marshmallow

Usage

Define your schemas as you would with marshmallow, but importing the Schema class from rest_marshmallow instead.

from rest_marshmallow import Schema, fields

class CustomerSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime()

The Schema class has the same interface as a Django REST framework serializer, so you can use it in your generic views...

class CustomerListView(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSchema

Or use the serializer API directly, for either serialization...

serializer = CustomerSchema(queryset, many=True)
return Response(serializer.data)

Or for validation...

serializer = CustomerSchema(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.validated_data

Instance create and update

If you want to support serializer.save() you'll need to define the .create() and/or .update() methods explicitly.

class CustomerSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime()

    def create(self, validated_data):
        return Customer.objects.create(**validated_data)

    def update(self, instance, validated_data):
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()
        return instance

You can now use .save() from your view code…

serializer = CustomerSchema(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

Or use the schema together with generic views that create or update instances...

class CustomerListView(generics.ListCreateAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSchema

Note that you should always use the create() and update() methods instead of overriding the make_object() marshmallow method.

Nested representations

For nested representations, use marshmallow's standard Nested field as usual.

from rest_marshmallow import fields, Schema

class ArtistSchema(Schema):
    name = fields.String()

class AlbumSchema(Schema):
    title = fields.String()
    release_date = fields.Date()
    artist = fields.Nested(ArtistSchema)

Excluding fields

The marshmallow only and exclude arguments are also valid as serializer arguments:

serializer = CustomerSchema(queryset, many=True, only=('name', 'email'))
return Response(serializer.data)

Testing

Install testing requirements.

$ pip install -r requirements.txt

Run with runtests.

$ ./runtests.py

You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run:

$ tox

Documentation

To build the documentation, you'll need to install mkdocs.

$ pip install mkdocs

To preview the documentation:

$ mkdocs serve
Running at: http://127.0.0.1:8000/

To build the documentation:

$ mkdocs build

django-rest-marshmallow's People

Contributors

davidzwa avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar devashishsharma2302 avatar droppoint avatar michaelwiles avatar pyup-bot avatar sloria avatar tomchristie avatar trnsnt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-rest-marshmallow's Issues

RelatedManager and Nested field

Made a small snippet for serializing relatedmanager objects (lazily sadly).

from marshmallow import ValidationError
from marshmallow.fields import Nested


class RelatedNested(Nested):

    def _serialize(self, nested_obj, attr, obj, **kwargs):
        # Load up the schema first. This allows a RegistryError to be raised
        # if an invalid schema name was passed
        schema = self.schema
        if nested_obj is None:
            return None
        try:
            return schema.dump(getattr(obj, attr).all(), many=self.many)
        except ValidationError as exc:
            raise ValidationError(exc.messages, valid_data=exc.valid_data) from exc

Any advice on whether using the obj directly is the right way?

support for fields.Dict()

Seems to exist in marshmallow but not in django-rest-marshmallow. Is there an easy workaround? I want to have a dict of string->string pairs in my schema

KWarg Partial is not passed to Schema at init

If I patch an object marshmallow validates all required fields and not partially, because Partial is not passed from the UpdateModelMixin partial_update function.

When I adjust the Marshmallow _schema_kwargs to include partial it starts working.

_schema_kwargs = ( 'only', 'exclude', 'dump_only', 'load_only', 'context', 'partial' )

TL;DR partial keyword is skipped in overidden DRF Schema.init(...)

fields.Nested() with many=True

I ran into an issue integrating this into my Django project. The offending line seemed to be

# Something other than 'object' of course
objects = fields.Nested(ObjectSerializer, many=True)

The error that was returned was

...
    return Response(serializer.data)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
    ret = super(ListSerializer, self).data
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/rest_marshmallow/__init__.py", line 34, in to_representation
    return self.dump(instance)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/schema.py", line 435, in dump
    index_errors=self.opts.index_errors,
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/marshalling.py", line 116, in serialize
    index=index,
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/marshalling.py", line 57, in call_and_store
    value = getter_func(data)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/marshalling.py", line 111, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/fields.py", line 262, in serialize
    return self._serialize(value, attr, obj, **kwargs)
  File "/Users/tyler/.virtualenvs/project/lib/python3.6/site-packages/marshmallow/fields.py", line 463, in _serialize
    return schema.dump(nested_obj, many=self.many)
AttributeError: 'ListSerializer' object has no attribute 'dump'

I made a small unit test addition and it looks like it fails as well.

class ManyNestedSerializer(Schema):
    top = fields.Integer()
    children = fields.Nested(ExampleSerializer, many=True)

def test_serialize_nested_many():
    instance = Object(top=1, children=[Object(number=123, text='abc') for i in range(3)])
    serializer = ExampleSerializer(instance)
    assert serializer.data == {'top': 1, 'children': [
        {'number': 123, 'text': 'abc'},
        {'number': 123, 'text': 'abc'},
        {'number': 123, 'text': 'abc'},
    ]}

---------------------------------

tests/test_marshmallow.py::test_serialize_nested_many FAILED                           [100%]

========================================== FAILURES ==========================================
_________________________________ test_serialize_nested_many _________________________________

    def test_serialize_nested_many():
        instance = Object(top=1, children=[Object(number=123, text='abc') for i in range(3)])
        serializer = ExampleSerializer(instance)
>       assert serializer.data == {'top': 1, 'children': [
            {'number': 123, 'text': 'abc'},
            {'number': 123, 'text': 'abc'},
            {'number': 123, 'text': 'abc'},
        ]}
E       AssertionError: assert {} == {'children': [{'number': 123..., 'text': 'abc'}], 'top': 1}
E         Right contains more items:
E         {'children': [{'number': 123, 'text': 'abc'},
E                       {'number': 123, 'text': 'abc'},
E                       {'number': 123, 'text': 'abc'}],
E          'top': 1}
E         Full diff:
E         - {}
E         + {'children': [{'number': 123, 'text': 'abc'},
E         +               {'number': 123, 'text': 'abc'},
E         +               {'number': 123, 'text': 'abc'}],
E         +  'top': 1}

tests/test_marshmallow.py:63: AssertionError

I see in the documentation that a single Nested instance is supported and tested, but should multiple nested objects be supported as well?


Django (2.1.5)
django-rest-marshmallow (3.1.1)
djangorestframework (3.9.0)
marshmallow (3.0.0rc1)

Marshmallow 3.0.1 - 'NoneType' object has no attribute 'opts'

Exception Value: 'NoneType' object has no attribute 'opts'

Description: when updating marshmallow from 3.0.0 to 3.0.1, all my API endpoints using any marshmallow serializer get this error. @sloria I am not sure if this is mmallow or django-mmallow
Expected behaviour: being able to use django 4.0+ and marshmallow 3.4 in combination with this interfacing library without error.

Pipfile extract:

Working version (before changing to marshmallow 3.0.1).

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
django-rainbowtests = "*"
psycopg2 = "*"

[packages]
...
django = "==2.1.15"
djangorestframework = "==3.10.2"
djangorestframework_simplejwt = "==4.4.0"
django-cors-headers = "==3.2.1"
django-rest-marshmallow = "~=4.0.1"
marshmallow = "==3.0.0"
django-url-filter = "==0.3.15"
...

[requires]
python_version = "3.7"

Complete error trace:

ERROR 2020-02-17 17:55:38,623 log 9152 6372 Internal Server Error: /api/v1/user/14/
Traceback (most recent call last):
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\views.py", line 497, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\views.py", line 457, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\views.py", line 468, in raise_uncaught_exception
    raise exc
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\views.py", line 494, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\mixins.py", line 56, in retrieve
    return Response(serializer.data)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_marshmallow\__init__.py", line 70, in data
    self._serializer_data = self.to_representation(self.instance)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_marshmallow\__init__.py", line 41, in to_representation
    return self.dump(instance)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 541, in dump
    result = self._serialize(processed_obj, many=many)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 505, in _serialize
    value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\fields.py", line 309, in serialize
    return self._serialize(value, attr, obj, **kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\fields.py", line 513, in _serialize
    schema = self.schema
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\fields.py", line 498, in schema
    dump_only=self._nested_normalized_option("dump_only"),
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\rest_marshmallow\__init__.py", line 36, in __init__
    MarshmallowSchema.__init__(self, **schema_kwargs)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 383, in __init__
    self.fields = self._init_fields()
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 913, in _init_fields
    self._bind_field(field_name, field_obj)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 969, in _bind_field
    field_obj._bind_to_schema(field_name, self)
  File "C:\Users\david\.virtualenvs\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\fields.py", line 1117, in _bind_to_schema
    or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)
AttributeError: 'NoneType' object has no attribute 'opts'

Serializing Date field in django-rest-marshmallow results in an error

I am using django-rest-marshmallow along with django-rest-framework to build simple APIs.
The following works if I dont include the created_at field in the serializer and gets the results as expected but upon inclusion, it throws an exception.

models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=50)
    created_at = models.DateField()

serializers.py

from rest_marshmallow import Schema, fields

class CategorySerializer(Schema):
    id = fields.Integer()
    name = fields.String()
    created_at = fields.Date() # works, if I dont include this

views.py

from rest_framework import viewsets

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

This results in the following error

Django version 2.2.5, using settings 'app.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /api/v1/categories/
Traceback (most recent call last):
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/mixins.py", line 45, in list
    serializer = self.get_serializer(queryset, many=True)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/generics.py", line 110, in get_serializer
    return serializer_class(*args, **kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_marshmallow/__init__.py", line 36, in __init__
    MarshmallowSchema.__init__(self, **schema_kwargs)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/marshmallow/schema.py", line 384, in __init__
    self._init_fields()
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/marshmallow/schema.py", line 915, in _init_fields
    self._bind_field(field_name, field_obj)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/marshmallow/schema.py", line 977, in _bind_field
    field_obj._bind_to_schema(field_name, self)
  File "/home/abcdefg/mpk/lib/python3.7/site-packages/marshmallow/fields.py", line 1181, in _bind_to_schema
    or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)
AttributeError: 'NoneType' object has no attribute 'opts'

Marsh 3.0.0: TypeError: validate_count() got an unexpected keyword argument 'partial'

Cant call serializer.is_valid() for marshmallow v3.0.0
@sloria

Trace:

Traceback (most recent call last):
File "...\ds4reboot\bierlijst\api\api_views.py", line 27, in turf_item
if not serializer.is_valid():
File "...\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\serializers.py", line 235, in is_valid
self.validated_data = self.run_validation(self.initial_data)
File "...\ds4reboot-pVDuRnsS\lib\site-packages\rest_framework\fields.py", line 542, in run_validation
value = self.to_internal_value(data)
File "...\ds4reboot-pVDuRnsS\lib\site-packages\rest_marshmallow_init
.py", line 50, in to_internal_value
return self.load(data)
File "...\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 684, in load
data, many=many, partial=partial, unknown=unknown, postprocess=True
File "...\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 825, in _do_load
field_errors=field_errors,
File "...\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 1105, in _invoke_schema_validators
partial=partial,
File "...\ds4reboot-pVDuRnsS\lib\site-packages\marshmallow\schema.py", line 729, in _run_validator
validator_func(output, partial=partial, many=many)
TypeError: validate_count() got an unexpected keyword argument 'partial'

get_attribute() takes exactly 2 arguments (4 given)

I am getting this error. Is it me doing something wrong or is it a bug. The problem seems to be happening because its using the get_attribute method in Field class of rest_framework and not the one defined in
BaseSchema class of Marshmallow.

Nested schema for Many To Many relations

Hello,

Not really sure if i am doing something wrong, but it seems like nested schema for many-to-many fields is not supported.
When i tried to just add,

many_to_many_field = fields.Nested(ManyToManyFieldSchema, many=True) it was failing bcs ManyToManyManager is not iterrable.

Managed to do it at the end, but i think its a bit hacky sollution
many_to_many_field = fields.Function(lambda obj: [ManyToManyFieldSchema().dump(many-to-many-instance) for many-to-many-instance in obj.many_to_many_field.all()])

Is there a better/correct way how to handle many to many fields serialization or its really not supported "out of the box"?

Thanks!

ModelSerializer support?

Is there any support for ModelSerializer?

It is useless to define all the fields again in the Schema.

How to use same schema for both Django and non-Django code?

Currently, it seems you have to use rest_marshmalow.* to replace marshmallow stuff. However, what if I want to use same schema in both Django- and non-Django code?

I see mostly bad options, e.g. use mostly Django version, and then do creative search-n-replace (rest_marshmallow => marshmallow) and cutting (redundant create/update methods in the schema objects).

This is more of a feature request than a bug I guess though..

Nested field throwing errors

Hi there, using the example provided in the README, i was trying the following:

My Django models:

# models.py

class Artist(models.Model):
    name = models.CharField(max_length=140)


class Album(models.Model):
    title = models.CharField(max_length=140)
    release_date = models.DateField()
    artist = models.ForeignKey(Artist)

The Marshmallow Schemas and DRF Viewsets:

# views.py

class ArtistSchema(Schema):
    name = fields.String()


class AlbumSchema(Schema):
    title = fields.String()
    release_date = fields.Date()
    artist = fields.Nested(ArtistSchema)


class ArtistViewSet(viewsets.ModelViewSet):
    queryset = Artist.objects.all()
    serializer_class = ArtistSchema


class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSchema

Finally, my URL configuration:

# urls.py

router = routers.DefaultRouter()
router.register(r'artists', ArtistViewSet, base_name='artists')
router.register(r'albums', AlbumViewSet, base_name='albums')


urlpatterns = [
    url(r'^api/', include(router.urls)),
]

When sending a HTTP GET to /api/albums/ i am geting the following trace:

Django version 1.10.5, using settings 'songify.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /api/albums/
Traceback (most recent call last):
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/viewsets.py", line 83, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list
    return Response(serializer.data)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/serializers.py", line 729, in data
    ret = super(ListSerializer, self).data
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/serializers.py", line 647, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/serializers.py", line 647, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_marshmallow/__init__.py", line 27, in to_representation
    return self.dump(instance).data
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/schema.py", line 511, in dump
    **kwargs
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/marshalling.py", line 147, in serialize
    index=(index if index_errors else None)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/marshalling.py", line 68, in call_and_store
    value = getter_func(data)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/marshalling.py", line 141, in <lambda>
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/fields.py", line 252, in serialize
    return self._serialize(value, attr, obj)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/fields.py", line 444, in _serialize
    schema = self.schema
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/marshmallow/fields.py", line 415, in schema
    dump_only=self._nested_normalized_option('dump_only'))
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_marshmallow/__init__.py", line 23, in __init__
    super(Schema, self).__init__(*args, **kwargs)
  File "/Users/k/.virtualenvs/songify/lib/python3.6/site-packages/rest_framework/serializers.py", line 118, in __init__
    super(BaseSerializer, self).__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'load_only'
[21/Feb/2017 22:06:44] "GET /api/albums/ HTTP/1.1" 500 16063

When i remove the artist = fields.Nested(ArtistSchema) from the AlbumSchema class, i receive a valid response without any errors. This is on Python 3.6, using the following package versions:

appdirs==1.4.0
Django==1.10.5
django-rest-marshmallow==2.0.0
djangorestframework==3.5.4
marshmallow==2.13.0
packaging==16.8
pyparsing==2.1.10
six==1.10.0

fields.Pluck does not work as expected

Code

class LSerializer(Schema):
    id = fields.Integer()
    last_name = fields.String()
    first_name = fields.String()

class RSerializer(Schema):
    id = fields.Integer()
    last_name = fields.Pluck(LSerializer, 'last_name')
    first_name = fields.Pluck(LSerializer, 'first_name')
    occupation = fields.String()

Response

{
    "id": 1
    "occupation": "Student"
}

Expected Response

{
    "id": 1,
    "first_name": "John",
    "last_name": "Appleseed",
    "occupation": "Student"
}

Pluck does not seem to work as expected or I'm not sure if I'm missing anything!

Add Azure Pipeline and add webhook to github

@sloria I can help set up Azure Pipelines. Do you have a reference pipeline file for travis I can take a look at?

On the pipeline matter:

  • What/where is the python matrix/strategy for TravisCI you currently use?
  • Are you using pytest?

On administration:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.