Login

URLMan serializer field for Django Rest Framework (DRF)

Author:
rixx
Posted:
August 13, 2019
Language:
Python
Version:
Not specified
Tags:
django-rest-framework urlman
Score:
0 (after 0 ratings)

This snippet shows how to add a url field to your API objects, which will then show up as an object in your JSON output.

As parameters, you can specify:

  • urls: A list of strings that exist on your URLMan class
  • attribute: The name of the URLMan class on your model, defaults to "urls"
  • full: If the full URLs including schema and hostname should be supplied, defaults to True
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from rest_framework.serializers import Field


class URLManField(Field):

    read_only = True
    write_only = False
    label = None
    source = '*'

    def __init__(self, *, urls, attribute='urls', full=True):
        self.urls = urls
        self.url_class = attribute
        self.full = full

    def to_representation(self, value):
        url_class = getattr(value, self.url_class)
        return {
            url: getattr(url_class, url).full() if self.full else getattr(url_class, url)
            for url in self.urls
        }

class MySerializer(ModelSerializer):
    urls = URLManField(urls=['login', 'logout', 'base'])

More like this

Comments

Please login first before commenting.