Updating an ManyToMany field with Django rest
我正在尝试设置此 API,以便可以使用"PUT"更新模型"MOVIE"中项目的一个/多个"TAG"。标签是 MOVIE 上的 M2M。我正在发布电影中项目的PK。
我的 httpie 工作(返回 200OK)但没有创建任何内容。当我发布整个 JSON(使用 fetch)时,它只会在 MOVIE(链接)上创建标签但没有 M2M 关系。
httpie
1 | http -f PUT http://localhost:8000/api/Edit/3/ tag:='{"name":"TEST"}' |
模型.py
1 2 3 4 5 6 7 | class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", null=True, blank=True) class Movie(models.Model): title = models.CharField("Whats happening?", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) |
序列化器.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Tag1Serializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name',) class EditSerializer(serializers.ModelSerializer): tag = Tag1Serializer(many=True, read_only=True) class Meta: model = Movie fields = ('title', 'tag', 'info', 'created', 'status') def update(self, instance, validated_data): import pdb; pdb.set_trace() tags_data = validated_data.pop('tag') for tag_data in tags_data: tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.get(**tag_data) instance.tag.add(tag) return movie |
Views.py
1 2 3 | class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer |
错误:
1 2 3 | Traceback tags_data = validated_data.pop('tag') KeyError: 'tag' |
drf 模型序列化程序类上没有
django 模型查询集也没有:
在确认调用了序列化方法后,也许你应该使用 drf test api 客户端为它编写一个测试,以便能够轻松发现错误:http://www.django-rest-framework.org/api-guide /testing/#apiclient
serializers.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'taglevel', 'id') class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) class Meta: model = Movie ordering = ('-created',) fields = ('title', 'pk', 'tag') def update(self, instance, validated_data): tags_data = validated_data.pop('tag') instance = super(MovieSerializer, self).update(instance, validated_data) for tag_data in tags_data: tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.create(**tag_data) instance.tag.add(tag) return instance |
tests.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class TestMovies(TestCase): def test_movies(self): movie = Movie.objects.create(title='original title') client = APIClient() response = client.put('/movies/{}/'.format(movie.id), { 'title': 'TEST title', 'tag': [ {'name': 'Test item', 'taglevel': 1} ] }, format='json') self.assertEqual(response.status_code, 200, response.content) # ...add more specific asserts |
好的。我答应等我弄明白了再回来。这可能不是完全数据安全的,因为 django 尚未验证传入的数据,所以我在我对 python 和 django 的相对无知中做出了一些假设。如果任何比我聪明的人可以扩展此答案,请联系我。
注意:我坚决遵守编写软件的清洁代码标准。多年来,它对我很有帮助。我知道它不是 Python 代码的元数据,但如果没有小的、紧密关注的方法,它会感觉很草率。
Views.py
如果你不能有骗子,你必须自己清除相关对象才能添加新对象。这是我能找到的为我的用例可靠地删除 m2m 的唯一方法。我需要确保没有重复,并且我需要一个原子模型。您的里程可能会有所不同。
1 2 3 4 5 6 7 8 | class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer def update(self, requiest, *args, **kwargs): movie = self.get_object() movie.tags.clear() return super().update(request, *args, **kwargs) |
序列化器.py
你必须挂钩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Tag1Serializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name',) class EditSerializer(serializers.ModelSerializer): tag = Tag1Serializer(many=True, read_only=True) class Meta: model = Movie fields = ('title', 'tag', 'info', 'created', 'status') def to_internal_value(self, data): movie_id = data.get('id') #if it's new, we can safely assume there's no related objects. #you can skip this bit if you can't make that assumption. if self.check_is_new_movie(movie_id): return super().to_internal_value(data) #it's not new, handle relations and then let the default do its thing self.save_data(movie_id, data) return super().to_internal_value(data) def check_is_new_movie(self, movie_id): return not movie_id def save_data(self, movie_id, data): movie = Movie.objects.filter(id=movie_id).first() #the data we have is raw json (string). Listify converts it to python primitives. tags_data = Utils.listify(data.get('tags')) for tag_data in tags_data: tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) #I am also assuming that the tag already exists. #If it doesn't, you have to handle that. if tag_qs.exists(): tag = tag_qs.first() movie.tags.add(tag) |
Utils.py
1 2 3 4 5 6 7 8 9 10 11 12 13 | from types import * class Utils: #python treats strings as iterables; this utility casts a string as a list and ignores iterables def listify(arg): if Utils.is_sequence(arg) and not isinstance(arg, dict): return arg return [arg,] def is_sequence(arg): if isinstance(arg, str): return False if hasattr(arg,"__iter__"): return True |
Test.py
根据需要调整 url 以使其正常工作。逻辑应该是正确的,但可能需要一些调整才能正确反映您的模型和序列化程序。它更复杂,因为我们必须为 APIClient 创建 json 数据以与 put 请求一起发送。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class MovieAPITest(APITestCase): def setUp(self): self.url = '/movies/' def test_add_tag(self): movie = Movie.objects.create(name="add_tag_movie") tag = Tag.objects.create(name="add_tag") movie_id = str(movie.id) url = self.url + movie_id + '/' data = EditSerializer(movie).data data.update({'tags': Tag1Serializer(tag).data}) json_data = json.dumps(data) self.client.put(url, json_data, content_type='application/json') self.assertEqual(movie.tags.count(), 1) |