I am using django-rest-framework-mongoengine for a personal project. I want to be able to send extra data in list requests. I have written 2 mixins for that purpose:
UserSearializerContextMixin: Collects the list of user ids for all the instances present in the list.
class UserSerializerContextMixin(object):
user_lookup_field = 'user_id'
user_fields_required = ['id','full_name','image','level']
_user_ids = []
def update_context(self,user_id):
if not self.context.get('user_ids'):
self.context['user_ids'] = [user_id]
else:
self.context['user_ids'].append(user_id)
def to_representation(self,instance):
self.update_context(getattr(instance,self.user_lookup_field))
return super(UserSerializerContextMixin,self).to_representation(instance)
UserSerializerDataMixin: Override the data property using the context prepared in to_representation part.
class UserSerializerDataMixin(object):
@property
def data(self):
ret = super(UserSerializerDataMixin, self).data
// Override the data
return ReturnDict(ret, serializer=self)
Then for my serializer I do something like this:
class DFSerializer(UserSerializerContextMixin,UserSerializerDataMixin,DocumentSerializer):
//Fields and all
But somehow the code just does not enter the overridden data property. I guess logically the data property should be overridden by extending the mixin. But it does not happen here.
What could possibly be the reason and how to resolve?
ListSerializer
. That's a nasty one. – Greasy