class MembershipSerializer(serializers.ModelSerializer): """Serializes CourseTeamMemberships with information about both teams and users.""" profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['public_fields'].append('url') user = ExpandableField(collapsed_serializer=CollapsedReferenceSerializer( model_class=User, id_source='username', view_name='accounts_api', read_only=True, ), expanded_serializer=UserReadOnlySerializer( configuration=profile_configuration)) team = ExpandableField( collapsed_serializer=CollapsedReferenceSerializer( model_class=CourseTeam, id_source='team_id', view_name='teams_detail', read_only=True, ), expanded_serializer=CourseTeamSerializerWithoutMembership( read_only=True), ) class Meta(object): model = CourseTeamMembership fields = ("user", "team", "date_joined", "last_activity_at") read_only_fields = ("date_joined", "last_activity_at")
class UserMembershipSerializer(serializers.ModelSerializer): """Serializes CourseTeamMemberships with only user and date_joined Used for listing team members. """ profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['public_fields'].append('url') user = ExpandableField( collapsed_serializer=CollapsedReferenceSerializer( model_class=User, id_source='username', view_name='accounts_api', read_only=True, ), expanded_serializer=UserReadOnlySerializer( configuration=profile_configuration), ) class Meta(object): """Defines meta information for the ModelSerializer.""" model = CourseTeamMembership fields = ("user", "date_joined") read_only_fields = ("date_joined", )
def test_serializer_data(self): """ Test serializer return data properly. """ UserProfile.objects.create(user=self.user, name='test name') data = UserReadOnlySerializer(self.user, configuration=self.config, context={'request': self.request}).data assert data['username'] == self.user.username assert data['name'] == 'test name' assert data['email'] == self.user.email
def test_user_no_profile(self): """ Test serializer return data properly when user does not have profile. """ with LogCapture(LOGGER_NAME, level=logging.DEBUG) as logger: data = UserReadOnlySerializer(self.user, configuration=self.config, context={'request': self.request}).data logger.check( (LOGGER_NAME, 'WARNING', 'user profile for the user [test_user] does not exist') ) assert data['username'] == self.user.username assert data['name'] is None
def get_user_readonly_serializer(*args, **kwargs): """ Returns the UserReadOnlySerializer. """ return UserReadOnlySerializer(*args, **kwargs)