Django Rest Framework'te İlişkili Modelin ID'si ile POST Request İşlemi
Django Rest Framework Post Request By Passing Related Field ID
models.py
xxxxxxxxxxfrom django.db import modelsclass Address(models.Model): country = models.CharField(max_length=120)class Customer(models.Model): name = models.CharField(max_length=120) address = models.ForeignKey(Address, on_delete=models.CASCADE)serializers.py
xxxxxxxxxxfrom rest_framework import serializers# internalfrom my.models import Address, Customerclass AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__'class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'address') # '__all__' da kullanılabilir def to_representation(self, instance): '''Bu methodu override ederek get,post,put işlemlerinde ilişkili modelin ID'sini vererek işlemlerimizi gerçekleştiriyoruz. ''' response = super().to_representation(instance) response['address'] = AddressSerializer(instance.address).data return responseviews.py
xxxxxxxxxxclass Customers(APIView): def get(self, request, format=None): customers = Customer.objects.all() serializer = CustomerSerializer(customers, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST)class CustomerDetail(APIView): def put(self, request, pk, format=None): customer = Customer.objects.get(pk=pk) serializer = CustomerSerializer(customer, 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 Customers, CustomerDetailurlpatterns = [ path('customers', Customers.as_view()), path('customers/<int:pk>', CustomerDetail.as_view()),]- URL
http://127.0.0.1:8000/my/customers - POST request data
{ "name":"Adnan", "address" : 1 }
- GET request
http://127.0.0.1:8000/my/customers
xxxxxxxxxxHTTP 200 OKAllow: GET, POST, HEAD, OPTIONSContent-Type: application/jsonVary: Accept[ { "id": 6, "name": "Adnan", "address": { "id": 1, "country": "Turkey" } }]- PUT request
http://127.0.0.1:8000/my/customers/1 { "name":"ADNAN2" , "address": 2 }- UPDATED (Güncellenmiş) data:
xxxxxxxxxx{ "id": 1, "name": "ADNAN2", "address": { "id": 2, "country": "Palestine" }}II. Yöntem Olarak
-serializers.py
xxxxxxxxxxclass CustomerSerializer(serializers.ModelSerializer): address = AddressSerializer(read_only=True) # post edeceğimiz data address_id alanını içermelidir. Çünkü PrimaryKeyRelatedField olarak address_id belirledik. address alanı address_id için kaynak oluşturmaktadır. address_id = serializers.PrimaryKeyRelatedField( write_only=True, source='address', queryset=Address.objects.all()) class Meta: model = Customer fields = ('id','name','address','address_id') # '__all__' da kullanılabilir.- POST request
{"name":"Kayace","address_id" : 1}
xxxxxxxxxx{ "id": 15, "name": "Kayace", "address": { "id": 1, "country": "Turkey" }}
Yorumlar