我正在尝试设置此API,以便可以使用“PUT”更新模型“MOVIE”中某个项目上的一个/多个“TAG”。标签是MOVIE上的M2M。我正在电影中发布该商品的PK。
我的httpie工作(返回200OK),但未创建任何内容。当我发布整个JSON(使用访存)时,它只是创建TAG,但在MOVIE(link)上没有M2M关系。
httpie
http -f PUT http://localhost:8000/api/Edit/3/ tag:='{"name": "TEST"}'
型号
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)
Serializers.py
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
class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
错误:
Traceback
tags_data = validated_data.pop('tag')
KeyError: 'tag'
最佳答案
好的。我答应了,我答应回来。这可能不是完全数据安全的,因为django尚未验证传入的数据,因此我在对python和django的相对了解中做出了一些假设。如果比我聪明的人都可以扩展这个答案,请打我一下。
注意:我坚决遵守书写软件的清洁代码标准。这些年来,它为我提供了很好的服务。我知道这不是Python代码的元数据,但是如果没有小型且重点突出的方法,它会显得草率。
Views.py
如果没有重复对象,则必须先清除相关对象,然后才能添加新对象。这是我可以为自己的用例可靠地删除m2m的唯一方法。我需要确保没有重复,并且希望有一个原子模型。你的旅费可能会改变。
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)
Serializers.py
由于验证器忽略m2m字段,因此必须挂接
to_internal_value
序列化器方法以获取所需的数据。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
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
调整网址以使其正常工作。逻辑应该正确,但可能需要进行一些调整才能正确反射(reflect)您的模型和序列化器。这更加复杂,因为我们必须为APIClient创建json数据以与put请求一起发送。
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)