Created
February 12, 2020 20:03
-
-
Save jsatt/e971e4a8f69f9377e9ea851e2b3ff204 to your computer and use it in GitHub Desktop.
Catalog serizalier and field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from catalog import CatalogMember | |
from collections import OrderedDict | |
from itertools import chain | |
from rest_framework.exceptions import APIException | |
from rest_framework.fields import ReadOnlyField | |
from rest_framework.serializers import Serializer | |
class CatalogSerializer(Serializer): | |
def __init__(self, *args, **kwargs): | |
if not hasattr(self, 'Meta') or not getattr(self.Meta, 'catalog'): | |
raise APIException('A catalog instance must be provided.') | |
super().__init__(*args, **kwargs) | |
def to_representation(self, obj): | |
if isinstance(obj, CatalogMember): | |
member = obj | |
else: | |
member = self.Meta.catalog(obj) | |
return super().to_representation(member) | |
def get_fields(self): | |
return OrderedDict( | |
(attr, ReadOnlyField()) | |
for attr in chain(self.Meta.catalog._attrs, ['name']) | |
if attr in getattr(self.Meta, 'fields', chain(self.Meta.catalog._attrs, ['name'])) | |
) | |
class CatalogField(ReadOnlyField): | |
def __init__(self, catalog, *args, display_attr=None, **kwargs): | |
self.catalog = catalog | |
self.display_attr = display_attr | |
super().__init__(*args, **kwargs) | |
def to_representation(self, obj): | |
if self.display_attr: | |
return getattr(self.catalog(obj), self.display_attr) | |
else: | |
return super().to_representation(vars(self.catalog(obj))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment