簡體   English   中英

使用 Django rest 更新 ManyToMany 字段

[英]Updating an ManyToMany field with Django rest

我正在嘗試設置此 API,以便我可以使用“PUT”來更新模型“MOVIE”中某個項目上的一個/多個“TAG”。 標簽是電影上的 M2M。 我正在發布電影中項目的PK。

我的 httpie 工作(返回 200OK)但沒有創建任何內容。 當我發布整個 JSON(使用 fetch)時,它只會在 MOVIE 上創建 TAG 但沒有 M2M 關系(鏈接)。

httpie

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

模型.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)

序列化器.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

視圖.py

class MovieViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

錯誤:

Traceback
    tags_data = validated_data.pop('tag')
KeyError: 'tag'

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 客戶端為其編寫一個測試,以便能夠輕松發現錯誤: http : //www.django-rest-framework.org/api-guide/testing/ #apiclient

序列化程序.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

測試.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

好的。 我答應當我想通了時會回來。 這可能不是完全數據安全的,因為 django 還沒有驗證傳入的數據,所以我在我對 python 和 django 的相對無知中做出了一些假設。 如果任何比我更聰明的人可以擴展這個答案,請聯系我。

注意:我堅定地遵守編寫軟件的 Clean Code 標准。 多年來,它對我很有幫助。 我知道這不是 Python 代碼的元數據,但是如果沒有小而專注的方法,它會讓人覺得草率。

視圖.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)

序列化器.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):
        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)

實用程序

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

測試文件

根據需要調整網址以使其正常工作。 邏輯應該是正確的,但可能需要進行一些調整才能正確反映您的模型和序列化程序。 它更復雜,因為我們必須為 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)

如果想在視圖函數中使用通用但簡單的東西,請參閱此處以獲取我的明確示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM