Skip to content

Instantly share code, notes, and snippets.

@mdogo
Created July 1, 2014 09:55
Show Gist options
  • Save mdogo/e7e2bc2158afd74c3e0f to your computer and use it in GitHub Desktop.
Save mdogo/e7e2bc2158afd74c3e0f to your computer and use it in GitHub Desktop.
Flat serializer for Django-rest-framework
class UserProfileSerializer(serializer.ModelSerializer):
class Meta:
model = UserProfile
fields = ['profile_info']
class UserSerializer(serializer.ModelSerializer):
profile_info = serializers.CharField(source='profile.profile_info')
class Meta:
model = User
fields = ['email', 'username']
"""
GET method does not need both serializers just the main one.
For POST, PATCH and PUT we need to initialize both serializer with the request data
and make all verification with both.
This code is not complete. When both objects are created(user and profile) they are not
related yet and maybe this will raise an exception (if profile.user can not be null).
"""
class CreateModelMixin(object):
def create(self, request, *args, **kwargs):
user_serializer = UserSerializer(data=request.DATA, files=request.FILES)
profile_serializer = UserProfileSerializer(data=request.DATA, files=request.FILES)
if user_serializer.is_valid() and profile_serializer.is_valid():
self.pre_save(user_serializer.object)
self.object = user_serializer.save(force_insert=True)
profile_serializer.save()
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
serializers_errors = user_serializer.errors.copy()
serializers_errors.update(user_profile_serializer.errors)
return Response(serializers_errors, status=status.HTTP_400_BAD_REQUEST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment