serialization - Django REST framework flat, read-write serializer -
in django rest framework, involved in creating flat, read-write serializer representation? docs refer 'flat representation' (end of section http://django-rest-framework.org/api-guide/serializers.html#dealing-with-nested-objects) don't offer examples or beyond suggestion use relatedfield
subclass.
for instance, how provide flat representation of user
, userprofile
relationship, below?
# model class userprofile(models.model): user = models.onetoonefield(user) favourite_number = models.integerfield() # serializer class userprofileserializer(serializers.modelserializer): email = serialisers.emailfield(source='user.email') class meta: model = userprofile fields = ['id', 'favourite_number', 'email',]
the above userprofileserializer
doesn't allow writing email
field, hope expresses intention sufficiently well. so, how should 'flat' read-write serializer constructed allow writable email
attribute on userprofileserializer
? @ possible when subclassing modelserializer?
thanks.
looking @ django rest framework (drf) source settled on view drf serializer tied accompanying model unserializing purposes. field
's source
param make less serializing purposes.
with in mind, , viewing serializers encapsulating validation , save behaviour (in addition (un)serializing behaviour) used 2 serializers: 1 each of user , userprofile models:
class userserializer(serializer.modelserializer): class meta: model = user fields = ['email',] class userprofileserializer(serializer.modelserializer): email = serializers.emailfield(source='user.email') class meta: model = userprofile fields = ['id', 'favourite_number', 'email',]
the source
param on emailfield
handles serialization case adequately (e.g. when servicing requests). unserializing (e.g. when serivicing put requests) necessary little work in view, combining validation , save behaviour of 2 serializers:
class userprofileretrieveupdate(generics.genericapiview): def get(self, request, *args, **kwargs): # userprofileserializer required serialize data since # email populated 'source' param on emailfield. serializer = userprofileserializer( instance=request.user.get_profile()) return response(serializer.data) def put(self, request, *args, **kwargs): # both userprofileserializer , userprofileserializer required # in order validate , save data on associated models. user_profile_serializer = userprofileserializer( instance=request.user.get_profile(), data=request.data) user_serializer = userserializer( instance=request.user, data=request.data) if user_profile_serializer.is_valid() , user_serializer.is_valid(): user_profile_serializer.save() user_serializer.save() return response( user_profile_serializer.data, status=status.http_200_ok) # combine errors both serializers. errors = dict() errors.update(user_profile_serializer.errors) errors.update(user_serializer.errors) return response(errors, status=status.http_400_bad_request)
Comments
Post a Comment