def list(self, request, *args, **kwargs): serializer_context = { 'request': request, } queryset = self.get_queryset() serializer = UserSerializer(queryset, context=serializer_context, many=True) return Response(serializer.data)
def get_users(request): serializer_context = { 'request': request, } users = User.objects.all() serializer = UserSerializer(users, context=serializer_context, many=True) return Response(serializer.data)
class ActivitySerializer(serializers.ModelSerializer): post = PostSerializer(read_only=True) user = UserSerializer(read_only=True) class Meta: model = models.Like fields = ("id", "post", "user")
class JobSerializer(serializers.ModelSerializer): def get_cName(self, obj): return obj.company.profile.cName cName = serializers.SerializerMethodField("get_cName") company = UserSerializer(read_only=True) requiredEducationLevel = serializers.CharField() class Meta: model = Job depth = 1 fields = [ "id", "cName", "company", "title", "requiredExperienceYears", "salary", "requiredEducationLevel", ] # to do set pk to slug def create(self, validated_data): diploma_pk = validated_data.pop("requiredEducationLevel") diploma = get_object_or_404(Diploma, pk=diploma_pk) job = Job.objects.create(**validated_data, requiredEducationLevel=diploma) return job
class ProfileSerializer(serializers.ModelSerializer): # user = serializers.ReadOnlyField(source='user.email') user = UserSerializer(read_only=True) class Meta: model = Profile fields = '__all__'
class FeedSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) parent_lookup_kwargs = { 'user_pk': 'user__pk', } class Meta: model = models.Post fields = "__all__"
class LikeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) def create(self, validated_data): return models.Like.objects.create(post=validated_data['post'], user=self.context['request'].user) class Meta: model = models.Like fields = "__all__"
class ProductSerializer(serializers.ModelSerializer): """ Private product serializer. CUD products of user is owner. More fields will be sent to the user. """ user = UserSerializer(read_only=True) class Meta: model = Product exclude = ('id',)
class ImageSerializer(serializers.HyperlinkedModelSerializer): # whitelist of content types, automatically updated when # HyperlinkedGalleryField is instantiated gallery_ct_whitelist = set() image = Base64ImageField() author = UserSerializer(read_only=True) class Meta: model = Image fields = 'id image caption author'.split()
def get_user_data(request): if request.method == 'GET': raw_token = request.META['HTTP_AUTHORIZATION'].split()[1] obj = JWTAuthentication( ) # create a class instance first to call the non-static method validated_token = obj.get_validated_token(raw_token) user = obj.get_user(validated_token) if user: data = {} user_data = UserSerializer(user).data return Response({'user': user_data, 'msg': 'success'}, status=200) else: return Response({'msg': 'user not found'}, status=404)
class PostSerializer(serializers.ModelSerializer): parent_lookup_kwargs = { 'user_pk': 'user__pk', } user = UserSerializer(read_only=True) class Meta: model = models.Post fields = "__all__" def create(self, validated_data): return models.Post.objects.create(**validated_data, user=self.context['request'].user)
class VerboseFruitSerializer(serializers.HyperlinkedModelSerializer): lng = serializers.DecimalField( max_digits=13, decimal_places=10, source='position.x', ) lat = serializers.DecimalField( max_digits=13, decimal_places=10, source='position.y', ) kind = KindRelatedField() time = serializers.DateTimeField( source='modified', format='%Y-%m-%d %H:%M:%S', required=False, read_only=True, ) # do not use HyperlinkedIdentityField because of slowness url = CachedHyperlinkedIdentityField(view_name='api:fruit-detail') user = UserSerializer(read_only=True) images_count = serializers.IntegerField(read_only=True) images = HyperlinkedGalleryField(gallery_ct='fruit') def create(self, validated_data): validated_data['position'] = Point( float(validated_data['position']['x']), float(validated_data['position']['y']), ) return super().create(validated_data) def update(self, instance, validated_data): position = validated_data.pop('position') if 'x' in position: instance.position.x = position['x'] if 'y' in position: instance.position.y = position['y'] return super().update(instance, validated_data) class Meta: model = Fruit fields = 'id lat lng kind time url description user images_count images'.split( )
def get(self, request, *args, **kwargs): data = {} pk = request.query_params.get('pk', None) if pk == None: data['response'] = 'Error' data['error_message'] = 'pk must be in the query parameters' return Response(data=data, status=status.HTTP_400_BAD_REQUEST) user = self.get_object() if user == Http404: data['response'] = 'User with pk does not exist' return Response(data=data, status=status.HTTP_404_NOT_FOUND) serializer = UserSerializer(user, context={'request': request}) data = serializer.data return Response(data=data, status=status.HTTP_200_OK)
def update_user_details(request, userId): if request.method == 'PATCH': if verify_user(request, userId): user = User.objects.get(id=userId) serializer = UserSerializer(user, data=request.data) data = {} if serializer.is_valid(): serializer.save() user = UserSerializer(user).data return Response({'user': user}, status=200) else: return Response(serializer.errors) else: return Response({'msg': 'Unable to verify credentials'}, status=400)
class VerboseFruitSerializer(serializers.HyperlinkedModelSerializer): lat = serializers.DecimalField( max_digits=13, decimal_places=10, source='latitude', ) lng = serializers.DecimalField( max_digits=13, decimal_places=10, source='longitude', ) kind = KindRelatedField() time = serializers.DateTimeField( source='modified', format='%Y-%m-%d %H:%M:%S', required=False, read_only=True, ) # do not use HyperlinkedIdentityField because of slowness url = CachedHyperlinkedIdentityField(view_name='api:fruit-detail') user = UserSerializer(read_only=True) images_count = serializers.IntegerField(read_only=True) images = HyperlinkedGalleryField(gallery_ct='fruit') class Meta: model = Fruit fields = 'id lat lng kind time url description user images_count images'.split( )
def get(self, request): serializer = UserSerializer(request.user) return Response(serializer.data)
class CommentSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = Comment fields = '__all__'
class OfferSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = Offer fields = "__all__"
def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data)