i'm doing an upgrade to DRF3.1.1 from 2.4. I was using a custom serializer to create an instance of an object that's not a Model.
In 2.4, it was easy enough to do this because in the serializer, I would create the object in restore_object(). In the view, i'd call serializer.is_valid() and then pop the instance of the object out of the serializer with serializer.object. Then I could do whatever I want.
With the 3.x changes, it's harder to get the instance out of the object because the create and update methods are supposed to do the saving, and "serializer.object" isn't available anymore.
As an example, I used to have this for my "UserRegistration" Object. This is not a model because it's a convenience object that the server parses up and stores data in a number of other objects/db tables.
class UserRegistration(object):
def __init__(self, full_name, stage_name, password="", email="", locale="en_US"):
self.full_name = full_name
self.password = password
self.locale = locale
self.email = email
self.stage_name = stage_name
Here's the associated DRF-2.4 serializer:
class UserRegistrationSerializer(serializers.Serializer):
full_name = serializers.CharField(max_length=128, required=False)
stage_name = serializers.CharField(max_length=128)
password = serializers.CharField(max_length=128, required=False)
locale = serializers.CharField(max_length=10, required=False)
# use CharField instead of EmailField for email. We do our own validation later to make for a better error msg.
email = serializers.CharField(max_length=254, required=False)
def restore_object(self, attrs, instance=None):
if instance is not None:
instance.full_name = attrs.get('full_name', instance.full_name)
instance.password = attrs.get('password', instance.password)
instance.locale = attrs.get('locale', instance.locale)
instance.email = attrs.get('email', instance.email)
instance.stage_name = attrs.get('stage_name', instance.stage_name)
return instance
return UserRegistration(**attrs)
Then in my view, I do something like this:
class UserRegistration(APIView):
throttle_classes = ()
serializer_class = UserRegistrationSerializer
def post(self, request, format=None):
event_type = "user_registration"
serializer = UserRegistrationSerializer(data=request.DATA, context={'request': request})
try:
if serializer.is_valid():
user_registration = serializer.object
# save user_registration pieces in various places...
However, in DRF3, I serializer.object is gone. The docs say to do "validation" using serializer.validated_data, but that's just a hash and not the real object. Is there a way to get the object?
The whole thing seems more married to DB objects, which in this particular case is exactly what i'm trying to avoid.
Am I just missing some new DRF3 concept?