def test_serialize_invalid_authors_data(self): long_name = 'a' * 256 author = {'name': long_name} serializer = AuthorSerializer(data=author) assert not serializer.is_valid() assert 'no more than 255 characters' in serializer.errors['name'][0]
def update(self, request, pk=None): try: item = Author.objects.get(pk=pk) except Author.DoesNotExist: return Response(status=404) serializer = AuthorSerializer(item, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400)
def test_retrive_authors(self, author, client): response = client.get(AUTHORS_URL) authors = AuthorModel.objects.all() serializer = AuthorSerializer(authors, many=True) assert response.status_code == status.HTTP_200_OK assert response.data == serializer.data
class BookSerializer(serializers.ModelSerializer): authors = AuthorSerializer(many=True, read_only=True) publisher = PublisherSerializer(read_only=True) class Meta: model = Book fields = ( 'id', 'title', 'image_url', 'api_url', 'authors', 'publisher', ) read_only = ( 'image_url', 'title', )
def test_serialize_valid_author(self, author): serializer = AuthorSerializer(author) assert serializer.data['name'] == author.name
def retrieve(self, request, pk=None): queryset = Author.objects.all() item = get_object_or_404(queryset, pk=pk) serializer = AuthorSerializer(item) return Response(serializer.data)
def create(self, request): serializer = AuthorSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)
def list(self, request): queryset = Author.objects.all() serializer = AuthorSerializer(queryset, many=True) return Response(serializer.data)