- Author:
- rixx
- Posted:
- August 13, 2019
- Language:
- Python
- Version:
- Not specified
- 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 classattribute
: 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 toTrue
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.