Skip to content

Instantly share code, notes, and snippets.

@sonthonaxrk
Created February 14, 2015 21:13
Show Gist options
  • Save sonthonaxrk/1da9a189d4fdfa0766d6 to your computer and use it in GitHub Desktop.
Save sonthonaxrk/1da9a189d4fdfa0766d6 to your computer and use it in GitHub Desktop.
{
"url": "https://api.localhost:8000/users/3/",
"first_name": "Steven ",
"last_name": "Konig",
"email": "stephen@example.com",
"profile-image": "https://fbcdn-profile-a.akamaihd.net/profile_picture.jpg",
"age": 36,
"profiles": {
"customer_profile_url": "https://api.localhost:8000/customers/3/",
"vendor_profile_url": "https://api.localhost:8000/vendors/3/"
}
},
class UserSerializer(serializers.HyperlinkedModelSerializer):
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
trim_user_data = self.context['request'].QUERY_PARAMS.get('trim_user_data')
if trim_user_data in ['true', '1', 'True']:
allowed = set(['url', 'id', 'profiles'])
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
profiles = serializers.SerializerMethodField()
def get_profiles(self, instance):
profile_dict = {}
if hasattr(instance, 'customerprofile'):
e = CustomerProfileSerializer(instance.customerprofile, context=self.context)
pdb.set_trace()
profile_dict['customer_profile_url'] = e['url'].value
if hasattr(instance, 'vendorprofile'):
e = VendorProfileSerializer(instance.vendorprofile, context=self.context )
profile_dict['vendor_profile_url'] = e['url'].value
return profile_dict
class Meta:
model = User
fields = ('url',
'id',
'first_name',
'last_name',
'get_full_name',
'email',
'profiles',
)
extra_kwargs={
'url':
{'view_name': 'user-detail'}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment