Skip to main content

Dynamically return subset of Django REST Framework serializer fields

Project description

Build status PyPI Version PyPI Downloads License is MIT

This package provides a mixin that allows the user to dynamically select only a subset of fields per resource.

Official version support:

  • Django 1.11, 2.0, 2.1

  • Supported REST Framework versions: 3.8, 3.9

  • Python 2.7 (deprecated), 3.4+

NOTE: Python 2 support is deprecated and will be removed in version 0.4.

Installing

pip install drf-dynamic-fields

What It Does

Example serializer:

class IdentitySerializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Identity
        fields = ('id', 'url', 'type', 'data')

A regular request returns all fields:

GET /identities

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5,
    "data": "John Doe"
  },
  ...
]

A query with the fields parameter on the other hand returns only a subset of the fields:

GET /identities/?fields=id,data

[
  {
    "id": 1,
    "data": "John Doe"
  },
  ...
]

And a query with the omit parameter excludes specified fields.

GET /identities/?omit=data

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5
  },
  ...
]

You can use both fields and omit in the same request!

GET /identities/?omit=data,fields=data,id

[
  {
    "id": 1
  },
  ...
]

Though why you would want to do something like that is beyond this author.

It also works on single objects!

GET /identities/1/?fields=id,data

{
  "id": 1,
  "data": "John Doe"
}

Usage

When defining a serializer, use the DynamicFieldsMixin:

from drf_dynamic_fields import DynamicFieldsMixin

class IdentitySerializer(DynamicFieldsMixin, serializers.ModelSerializer):
    class Meta:
        model = models.Identity
        fields = ('id', 'url', 'type', 'data')

The mixin needs access to the request object. Some DRF classes like the ModelViewSet set that by default, but if you handle serializers yourself, pass in the request through the context:

events = Event.objects.all()
serializer = EventSerializer(events, many=True, context={'request': request})

Warnings

If the request context does not have access to the request, a warning is emitted:

UserWarning: Context does not have access to request.

First, make sure that you are passing the request to the serializer context (see “Usage” section).

There are some cases (e.g. nested serializers) where you cannot get rid of the warning that way (see issue 27). In that case, you can silence the warning through settings.py:

DRF_DYNAMIC_FIELDS = {
   'SUPPRESS_CONTEXT_WARNING': True,
}

Scope

This library is about filtering fields based on individual requests. It is deliberately kept simple and we do not plan to add new features. Feel free to contribute improvements, code simplifications and bugfixes though! (See also: #18)

If you need more advanced filtering features, maybe drf-flex-fields could be something for you.

Testing

To run tests, install Django and DRF and then run runtests.py:

$ python runtests.py

Credits

  • The implementation is based on this StackOverflow answer. Thanks YAtOff!

  • The GitHub users X17 and rawbeans provided improvements on my gist that were incorporated into this library. Thanks!

  • For other contributors, please see Github contributor stats.

License

MIT license, see LICENSE file.

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

drf_dynamic_fields-0.3.1.tar.gz (4.4 kB view details)

Uploaded Source

Built Distribution

drf_dynamic_fields-0.3.1-py2.py3-none-any.whl (5.4 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file drf_dynamic_fields-0.3.1.tar.gz.

File metadata

  • Download URL: drf_dynamic_fields-0.3.1.tar.gz
  • Upload date:
  • Size: 4.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.1 setuptools/40.6.2 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.7.1

File hashes

Hashes for drf_dynamic_fields-0.3.1.tar.gz
Algorithm Hash digest
SHA256 de75969abff74332f339d082931f1815dc91c2ff1ed6e741bd33d1d5057dceb1
MD5 ad5bf411b0de836084ba6d50463466eb
BLAKE2b-256 0bca4e9a2aa43b311a4b30c012e579ff424ae3ab1e0ef74598a727872aeb3ec5

See more details on using hashes here.

File details

Details for the file drf_dynamic_fields-0.3.1-py2.py3-none-any.whl.

File metadata

  • Download URL: drf_dynamic_fields-0.3.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.1 setuptools/40.6.2 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.7.1

File hashes

Hashes for drf_dynamic_fields-0.3.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 fa5a7ea010476184d776b4b977d57d0090e651e8f897d83ed0c2f2bca9cbf704
MD5 de2469e837ac3d9dddb0f7877fe7fa42
BLAKE2b-256 56a5a8a7a8ab55266489e25bc8947af25572d0f72a1685f9cd7e2ff7bd6d4fe7

See more details on using hashes here.

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