def get_next_photo_list(request): """ 获取下一个随机 n 个 photo, n 默认为 5 --- parameters: - name: limit type: integer paramType: query required: false serializer: PhotoSerializer responseMessages: - code: 400 message: prama error """ limit = request.GET.get('limit', 5) query_set = Photo.objects.all() random_query_set = set([]) length = len(query_set) while (len(random_query_set) < int(limit)): rand_int = random.randint(0, length - 1) random_query_set.add(query_set[rand_int]) serializer = PhotoSerializer(random_query_set) return Response(serializer.data, status=status.HTTP_200_OK)
def list_my_photo(request): """ 获得我(当前 member)发过的 photo 的全部列表,并且每一项都是详细信息 --- serializer: PhotoSerializer responseMessages: - code: 400 message: prama error """ member = request.member query_set = Photo.objects.filter(member=member) serializer = PhotoSerializer(query_set, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def like_photo(request, photo_id=None): """ 赞一个 photo --- serializer: PhotoSerializer responseMessages: - code: 400 message: prama error """ member = request.member photo = Photo.objects.get(pk=photo_id) photo.likes.add(member) serializer = PhotoSerializer(photo) return Response(serializer.data, status=status.HTTP_200_OK)
def list_my_like(request): """ 获得我(当前 member)赞过的 photo 的全部列表, 并且每一项都是详细信息 --- serializer: PhotoSerializer responseMessages: - code: 400 message: prama error """ member = request.member query_set = member.like_photos.all() serializer = PhotoSerializer(query_set, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
class ProjectSerializer(serializers.ModelSerializer): photos = PhotoSerializer(source="photo_set", many=True) class Meta: model = Project fields = ["title", "email_address", "photos"] def create(self, validated_data): photo_data = validated_data.pop('photo_set') photo_data = [dict(x)['photo'] for x in photo_data] project, created = Project.objects.get_or_create(**validated_data) for photo in photo_data: print(dir(photo)) Photo.objects.create(project=project, photo=photo) return project
class FaceSerializer(serializers.ModelSerializer): photo = PhotoSerializer(read_only=True) class Meta: model = Face exclude = ('encoding', )
def post(self, request): serializer = PhotoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request): photos = Photo.objects.all() serializer = PhotoSerializer(photos, many=True) return Response(serializer.data)