[Django] 23 - DRF: Add Ingredient API
Ref: https://www.udemy.com/course/django-python-advanced/learn/lecture/32236808#notes 104-109
Model
-
Test Case
def test_create_ingredient(self): """Test creating an ingredient is successful."""
user = create_user() # Next, go adhead to create model. ingredient = models.Ingredient.objects.create( user=user, name='Ingredient1' ) self.assertEqual(str(ingredient), ingredient.name)
-
Model Implementation
class Ingredient(models.Model): """Ingredient for recipes.""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name
Recipe内部也要跟进。
class Recipe(models.Model): """Recipe object.""" ... ... # 90-2 add, then register in admin. tags = models.ManyToManyField('Tag') ingredients = models.ManyToManyField('Ingredient')
admin.site.register(models.Tag)
admin.site.register(models.Ingredient)
View
-
Test Case
class PublicIngredientsApiTests(TestCase): """Test unauthenticated API requests.""" def setUp(self): self.client = APIClient() def test_auth_required(self): """Test auth is required for retrieving ingredients.""" res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateIngredientsApiTests(TestCase): """Test authenticated API requests.""" def setUp(self): self.user= create_user() self.client= APIClient() self.client.force_authenticate(self.user) def test_retrieve_ingredients(self): """Test retrieving a list of ingredients.""" Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Vanilla') res = self.client.get(INGREDIENTS_URL) # 获得了两个object的信息 ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_ingredients_limited_to_user(self): """Test list of ingredients is limited to authenticated user.""" user2 = create_user(email='user2@example.com') ret = Ingredient.objects.create(user=user2, name='Salt') # <---- 另外一个 user ingredient = Ingredient.objects.create(user=self.user, name='Pepper') res = self.client.get(INGREDIENTS_URL)
# 这里专门只检查了一个属于该user的ingredient self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) # 因为是不同的用户,所以这里只会出现该用户的一个数据 self.assertEqual(res.data[0]['name'], ingredient.name) self.assertEqual(res.data[0]['id'], ingredient.id)
# ------------------------------------------------------------------------------------------
def test_update_ingredient(self): """Test updating an ingredient.""" ingredient = Ingredient.objects.create(user=self.user, name='Cilantro') payload = {'name': 'Coriander'} url = detail_url(ingredient.id) res = self.client.patch(url, payload) self.assertEqual(res.status_code, status.HTTP_200_OK) ingredient.refresh_from_db() self.assertEqual(ingredient.name, payload['name']) def test_delete_ingredient(self): """Test deleting an ingredient.""" ingredient = Ingredient.objects.create(user=self.user, name='Lettuce') url = detail_url(ingredient.id) res = self.client.delete(url) self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) ingredients = Ingredient.objects.filter(user=self.user) self.assertFalse(ingredients.exists())
-
Serializers
class IngredientSerializer(serializers.ModelSerializer): """Serializer for ingredients.""" class Meta: model = Ingredient fields = ['id', 'name'] read_only_fields = ['id']
-
View
自己实现了一个基类:BaseRecipeAttrViewSet。
More: [Django] 21 - DRF: APIView vs Viewsets
class BaseRecipeAttrViewSet(mixins.DestroyModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """Base viewset for recipe attributes."""
authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): """Filter queryset to authenticated user.""" return self.queryset.filter(user=self.request.user).order_by('-name') class IngredientViewSet(BaseRecipeAttrViewSet): """Manage ingredients in the database."""
serializer_class = serializers.IngredientSerializer queryset = Ingredient.objects.all()
Create a recipe with new ingredients
Recipe
-
Test Case
文件 test_recipe_api.py
def test_create_recipe_with_new_ingredients(self): """Test creating a recipe with new ingredients."""
payload = { 'title': 'Cauliflower Tacos', 'time_minutes': 60, 'price': Decimal('4.30'), 'ingredients': [{'name': 'Cauliflower'}, {'name': 'Salt'}], # 顺便也创建了ingredients object } res = self.client.post(RECIPES_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipes = Recipe.objects.filter(user=self.user) self.assertEqual(recipes.count(), 1) recipe = recipes[0] self.assertEqual(recipe.ingredients.count(), 2) for ingredient in payload['ingredients']: exists = recipe.ingredients.filter( name=ingredient['name'], user=self.user, ).exists() self.assertTrue(exists) def test_create_recipe_with_existing_ingredient(self): """Test creating a new recipe with existing ingredient."""
ingredient = Ingredient.objects.create(user=self.user, name='Lemon') payload = { 'title': 'Vietnamese Soup', 'time_minutes': 25, 'price': '2.55', 'ingredients': [{'name': 'Lemon'}, {'name': 'Fish Sauce'}], } res = self.client.post(RECIPES_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipes = Recipe.objects.filter(user=self.user) self.assertEqual(recipes.count(), 1) recipe = recipes[0] self.assertEqual(recipe.ingredients.count(), 2) self.assertIn(ingredient, recipe.ingredients.all()) for ingredient in payload['ingredients']: exists = recipe.ingredients.filter( name=ingredient['name'], user=self.user, ).exists() self.assertTrue(exists) def test_create_ingredient_on_update(self):
"""Test creating an ingredient when updating a recipe."""
recipe = create_recipe(user=self.user) payload = {'ingredients': [{'name': 'Limes'}]} url = detail_url(recipe.id) res = self.client.patch(url, payload, format='json') self.assertEqual(res.status_code, status.HTTP_200_OK) new_ingredient = Ingredient.objects.get(user=self.user, name='Limes') self.assertIn(new_ingredient, recipe.ingredients.all()) def test_update_recipe_assign_ingredient(self): """Test assigning an existing ingredient when updating a recipe."""
ingredient1 = Ingredient.objects.create(user=self.user, name='Pepper') recipe = create_recipe(user=self.user) recipe.ingredients.add(ingredient1) ingredient2 = Ingredient.objects.create(user=self.user, name='Chili') payload = {'ingredients': [{'name': 'Chili'}]} url = detail_url(recipe.id) res = self.client.patch(url, payload, format='json') self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn(ingredient2, recipe.ingredients.all()) self.assertNotIn(ingredient1, recipe.ingredients.all()) def test_clear_recipe_ingredients(self): """Test clearing a recipes ingredients."""
ingredient = Ingredient.objects.create(user=self.user, name='Garlic') recipe = create_recipe(user=self.user) recipe.ingredients.add(ingredient) payload = {'ingredients': []} url = detail_url(recipe.id) res = self.client.patch(url, payload, format='json') self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(recipe.ingredients.count(), 0)
-
Serializers
recipe 中相应的 ingredients 部分需要更新。
class RecipeSerializer(serializers.ModelSerializer): """Serializer for recipes."""tags= TagSerializer(many=True, required=False) ingredients = IngredientSerializer(many=True, required=False) class Meta: model = Recipe fields = [ 'id', 'title', 'time_minutes', 'price', 'link', 'tags', 'ingredients', ] read_only_fields = ['id'] class RecipeDetailSerializer(RecipeSerializer): """Serializer for recipe detail view.""" class Meta(RecipeSerializer.Meta): fields = RecipeSerializer.Meta.fields + ['description'] def _get_or_create_tags(self, tags, recipe): """Handle getting or creating tags as needed.""" auth_user = self.context['request'].user for tag in tags: tag_obj, created = Tag.objects.get_or_create( user=auth_user, **tag, ) recipe.tags.add(tag_obj) def _get_or_create_ingredients(self, ingredients, recipe): """Handle getting or creating ingredients as needed.""" auth_user = self.context['request'].user for ingredient in ingredients: ingredient_obj, created = Ingredient.objects.get_or_create( user=auth_user, **ingredient, ) recipe.ingredients.add(ingredient_obj) def create(self, validated_data): """Create a recipe.""" tags = validated_data.pop('tags', []) # <-- ingredients = validated_data.pop('ingredients', []) # <-- recipe = Recipe.objects.create(**validated_data)
self._get_or_create_tags(tags, recipe) # ----> self._get_or_create_ingredients(ingredients, recipe) # ----> return recipe def update(self, instance, validated_data): """Update recipe.""" tags = validated_data.pop('tags', None) ingredients = validated_data.pop('ingredients', None) if tags is not None: instance.tags.clear() self._get_or_create_tags(tags, instance) if ingredients is not None: instance.ingredients.clear() self._get_or_create_ingredients(ingredients, instance) for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance
Not support writable nested fields by default
$ source pytest.sh Starting c2-recipe-app-api-2_db_1 ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). ............FF.FFFFFF.FF..FF.........................Waiting for database... Database unavailable, waiting 1 second... Database unavailable, waiting 1 second... Database unavailable, waiting 1 second... Database unavailable, waiting 1 second... Database unavailable, waiting 1 second... Database available! .Waiting for database... Database available! . ====================================================================== FAIL: test_clear_album_photos (dataset.tests.test_album_api.PrivateAlbumApiTests) Test clearing a albums photos. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 368, in test_clear_album_photos res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_clear_album_tags (dataset.tests.test_album_api.PrivateAlbumApiTests) Test clearing a albums tags. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 282, in test_clear_album_tags res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_album_with_existing_photo (dataset.tests.test_album_api.PrivateAlbumApiTests) Test creating a new album with existing photo. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 318, in test_create_album_with_existing_photo res = self.client.post(ALBUMS_URL, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 209, in post return self.generic('POST', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/app/dataset/views.py", line 39, in perform_create serializer.save(user=self.request.user) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 205, in save self.instance = self.create(validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 925, in create raise_errors_on_nested_writes('create', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_album_with_existing_tags (dataset.tests.test_album_api.PrivateAlbumApiTests) Test creating a album with existing tag. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 232, in test_create_album_with_existing_tags res = self.client.post(ALBUMS_URL, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 209, in post return self.generic('POST', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/app/dataset/views.py", line 39, in perform_create serializer.save(user=self.request.user) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 205, in save self.instance = self.create(validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 925, in create raise_errors_on_nested_writes('create', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_album_with_new_photos (dataset.tests.test_album_api.PrivateAlbumApiTests) Test creating a album with new photos. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 295, in test_create_album_with_new_photos res = self.client.post(ALBUMS_URL, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 209, in post return self.generic('POST', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/app/dataset/views.py", line 39, in perform_create serializer.save(user=self.request.user) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 205, in save self.instance = self.create(validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 925, in create raise_errors_on_nested_writes('create', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_album_with_new_tags (dataset.tests.test_album_api.PrivateAlbumApiTests) Test creating a album with new tags. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 209, in test_create_album_with_new_tags res = self.client.post(ALBUMS_URL, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 209, in post return self.generic('POST', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/app/dataset/views.py", line 39, in perform_create serializer.save(user=self.request.user) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 205, in save self.instance = self.create(validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 925, in create raise_errors_on_nested_writes('create', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_photo_on_update (dataset.tests.test_album_api.PrivateAlbumApiTests) Test creating an photo when updating a album. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 339, in test_create_photo_on_update res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_create_tag_on_update (dataset.tests.test_album_api.PrivateAlbumApiTests) Test create tag when updating a album. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 253, in test_create_tag_on_update res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_full_update (dataset.tests.test_album_api.PrivateAlbumApiTests) Test full update of album. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 165, in test_full_update self.assertEqual(getattr(album, k), v) AssertionError: 'Sample album description.' != 'New album description' - Sample album description. ? ^^^^^ - + New album description ? ^ + ====================================================================== FAIL: test_get_album_detail (dataset.tests.test_album_api.PrivateAlbumApiTests) Test get album detail. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 107, in test_get_album_detail self.assertEqual(res.data, serializer.data) AssertionError: {'id'[113 chars] 'tags': [], 'photos': []} != {'id'[113 chars] 'tags': [], 'photos': [], 'description': 'Sample description'} ====================================================================== FAIL: test_update_album_assign_photo (dataset.tests.test_album_api.PrivateAlbumApiTests) Test assigning an existing photo when updating a album. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 354, in test_update_album_assign_photo res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ====================================================================== FAIL: test_update_album_assign_tag (dataset.tests.test_album_api.PrivateAlbumApiTests) Test assigning an existing tag when updating a album. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/dataset/tests/test_album_api.py", line 268, in test_update_album_assign_tag res = self.client.patch(url, payload, format='json') File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 311, in patch response = super().patch( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 217, in patch return self.generic('PATCH', path, data, content_type, **extra) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/py/lib/python3.9/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/py/lib/python3.9/site-packages/django/test/client.py", line 719, in request self.check_exception(response) File "/py/lib/python3.9/site-packages/django/test/client.py", line 580, in check_exception raise exc_value File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/py/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 200, in save self.instance = self.update(self.instance, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 969, in update raise_errors_on_nested_writes('update', self, validated_data) File "/py/lib/python3.9/site-packages/rest_framework/serializers.py", line 790, in raise_errors_on_nested_writes assert not any( AssertionError: The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields. ---------------------------------------------------------------------- Ran 55 tests in 9.716s FAILED (failures=12) Destroying test database for alias 'default'...
AssertionError: The `.update()` method does not support writable nested fields by default.
Write an explicit `.update()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields.
AssertionError: The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `dataset.serializers.AlbumSerializer`, or set `read_only=True` on nested serializer fields.
????