使用Django rest更新ManyToMany字段

时间:2016-10-19 23:44:07

标签: python django django-rest-framework

我正在尝试设置此API,以便我可以使用“PUT”更新模型“MOVIE”中项目的一个/多个“TAG”。标签是MOVIE上的M2M。我发布了电影中项目的PK。

我的httpie工作(返回200OK)但没有创建任何内容。当我发布整个JSON(使用fetch)时,它只是在MOVIE(link)上创建TAG但没有M2M关系。

httpie

http -f PUT http://localhost:8000/api/Edit/3/ tag:='{"name": "TEST"}'

Models.py

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'

3 个答案:

答案 0 :(得分:5)

drf模型序列化程序类上没有put方法,因此没有调用put(self, validated_data)。使用:update(self, instance, validated_data)代替。保存实例的文档:http://www.django-rest-framework.org/api-guide/serializers/#saving-instances

django模型查询集也没有它:Movie.objects.putTag.objects.put。您已经拥有电影的instance参数,如果您要查询标签,则可能需要Tag.objects.getTag.objects.filter? QuerySet API参考:https://docs.djangoproject.com/en/1.10/ref/models/querysets/#queryset-api

在验证序列化程序方法被调用之后,您可能应该使用drf test api client为它编写测试,以便能够轻松发现错误:http://www.django-rest-framework.org/api-guide/testing/#apiclient

serializers.py

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

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

答案 1 :(得分:2)

好。当我想出来时,我答应回来。这可能不完全是数据安全的,因为django还没有验证传入的数据,所以我在对python和django的相对无知中做了一些假设。如果有人比我更聪明,可以扩大这个答案,请打我。

注意:我坚定地遵守Clean Code编写软件的标准。多年来它一直很好。我知道它不是Python代码的元素,但是如果没有小型,紧密集中的方法,它就会感到邋..

<强> Views.py

如果您不能使用dupes,则必须先自行清除相关对象,然后才能添加新对象。这是我能找到的唯一方法可靠地删除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

您必须挂钩to_internal_value序列化程序方法才能获取所需的数据,因为验证程序会忽略m2m字段。

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):
        if not movie_id:
            return True
        return False

    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

根据需要调整网址以使其正常工作。逻辑应该是正确的,但可能需要一些调整才能正确反映您的模型和序列化器。它更复杂,因为我们必须为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)

答案 2 :(得分:0)

如果想在视图函数中使用通用但简单的内容,请参见此处的清晰示例:

https://stackoverflow.com/a/55043187/5626788