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
xxxxxxxxxx
from django.db import models
class 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
xxxxxxxxxx
from rest_framework import serializers
# internal
from my.models import Address, Customer
class 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 response
views.py
xxxxxxxxxx
class 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
xxxxxxxxxx
from django.urls import path
# internal
from my.views import Customers, CustomerDetail
urlpatterns = [
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
xxxxxxxxxx
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: 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
xxxxxxxxxx
class 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