<s> from collections import OrderedDict <EOL> from rest_framework . fields import empty <EOL> from django . utils . functional import cached_property <EOL> class Mixin ( object ) : <EOL> ordered = False <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> self . ordered = kwargs . pop ( '<STR_LIT>' , self . ordered ) <EOL> super ( Mixin , self ) . __init__ ( * args , ** kwargs ) <EOL> def obj_to_representation ( self , obj ) : <EOL> data = [ ( f , getattr ( obj , f . field_name ) ) for <EOL> f in self . repr_fields ] <EOL> if self . ordered : <EOL> return OrderedDict ( <EOL> [ ( f . field_name , f . to_representation ( val ) if val else None ) <EOL> for f , val in data ] ) <EOL> else : <EOL> return dict ( <EOL> [ ( f . field_name , f . to_representation ( val ) if val else None ) <EOL> for f , val in data ] ) <EOL> def dict_to_representation ( self , d ) : <EOL> data = [ ( f , d . get ( f . field_name , None ) ) for <EOL> f in self . repr_fields ] <EOL> if self . ordered : <EOL> return OrderedDict ( <EOL> [ ( f . field_name , f . to_representation ( val ) if val else None ) <EOL> for f , val in data ] ) <EOL> else : <EOL> return dict ( <EOL> [ ( f . field_name , f . to_representation ( val ) if val else None ) <EOL> for f , val in data ] ) <EOL> @ cached_property <EOL> def repr_fields ( self ) : <EOL> return [ field for field in self . fields . values ( ) <EOL> if ( not field . read_only ) or ( field . default is not empty ) ] <EOL> obj_to_representation = Mixin . obj_to_representation <EOL> dict_to_representation = Mixin . dict_to_representation </s>
