Django Rest Framework'te Many To Many Serializtaion
models.py
xxxxxxxxxxfrom django.db import modelsclass Tag(models.Model): name = models.CharField(max_length=20)class Post(models.Model): title = models.CharField(max_length=120) tags = models.ManyToManyField(Tag, related_name="post")serializers.py
xxxxxxxxxxfrom rest_framework import serializers# internalfrom my.models import Post, Tagclass TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__'class PostSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) class Meta: model = Post fields = ('id', 'title', 'tags')views.py
xxxxxxxxxxclass Posts(APIView): def get(self, request, format=None): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)class PostDetail(APIView): def get(self, request, pk, format=None): post = Post.objects.get(pk=pk) serializer = PostSerializer(post) return Response(serializer.data) def put(self, request, pk, format=None): post = Post.objects.get(pk=pk) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)urls.py
xxxxxxxxxxfrom django.urls import path# internalfrom my.views import Posts, PostDetailurlpatterns = [ path('posts', Posts.as_view()), path('posts/<int:pk>', PostDetail.as_view()),]- URL
http://127.0.0.1:8000/my/posts - POST request data
xxxxxxxxxx{ "title":"Strong and Big Programming", "tags" : [2,4] }- Kaydedilen data
xxxxxxxxxx{ "id": 28, "title": "Strong and Big Programming", "tags": [ 2, 4 ]}- GET request
http://127.0.0.1:8000/my/customers
xxxxxxxxxxHTTP 200 OKAllow: GET, POST, HEAD, OPTIONSContent-Type: application/jsonVary: Accept[ { "id": 27, "title": "Fast and Simple Programming", "tags": [ 1, 4 ] }, { "id": 28, "title": "Strong and Big Programming", "tags": [ 2, 4 ] }]- PUT request
http://127.0.0.1:8000/my/posts/27
xxxxxxxxxx{ "id" : 27, "title": "Fast and Very Simple Programming", "tags" : [1,4]}- UPDATED (Güncellenmiş) data:
xxxxxxxxxx{ "id": 27, "title": "Fast and Very Simple Programming", "tags": [ 1, 4 ]}Another way (Diğer Yöntem)
serializers.py
xxxxxxxxxxclass PostSerializer2(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title', 'tags') def create(self, validated_data): tags = validated_data.pop('tags') post = Post.objects.create(**validated_data) for tag in tags: post.tags.add(tag) return postPostSerializer2'yiviews.py'da kullanırsanız aynı sonucu alacaksınız.- POST request yapalım yine
http://127.0.0.1:8000/my/posts
xxxxxxxxxx{ "title":"Best Languages and Frameworks", "tags" : [ 4,3,2,1 ] }- Yine ID'leri dizi olarak verdik.
- Kaydedilen veri
xxxxxxxxxx{ "id": 32, "title": "Best Languages and Frameworks", "tags": [ 1, 2, 3, 4 ]}- PUT request
http://127.0.0.1:8000/my/posts/32 - data:
xxxxxxxxxx{ "title":"Best languages and frameworks updated", "tags" : [ 2,1 ] }- Güncellenmiş (updated) data
xxxxxxxxxx{ "id": 33, "title": "Best languages and frameworks updated", "tags": [ 1, 2 ]}
Yorumlar