I'm new to using the Django Rest Framework and serialized data, I'm trying to update a nested serializer but ran into a wall, I've looked around but most people have problems in the serializers.py side while I can't even get into def update without an error, these are my classes:
Views.py
from django.shortcuts import render
from rest_framework import generics
from api.serializers import ProfileSerializer
from django.contrib.auth.models import User
from api.models import Profile
from django.http import JsonResponse
class ProfileView(generics.ListCreateAPIView):
def get(self, request):
profile = Profile.objects.filter(user_id=request.user.id)
serializer = ProfileSerializer(profile, many=True)
return JsonResponse(serializer.data, safe=False)
def post(self, request, *args, **kwargs):
profile = Profile.objects.filter(user_id=request.user.id)
data = request.POST
serializer = ProfileSerializer(profile, data=data, partial=True)
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors)
return JsonResponse(serializer.data, safe=False)
Serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from api.models import Profile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','first_name','last_name','email','last_login','date_joined','is_active')
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Profile
fields = ('id','phone','birth_date','user')
def update(self, instance, validated_data):
#Cant get here
print("hey")
return instance
Sample structure
[
{
"id": 3,
"phone": "XXXXXX",
"birth_date": "2017-06-29",
"user": {
"id": 1,
"username": "xxxxx",
"first_name": "XXXXX",
"last_name": "XXXX",
"email": "[email protected]",
"last_login": "2017-06-29T15:16:11.438818Z",
"date_joined": "2017-06-23T16:48:38Z",
"is_active": true
}
}
]
My current error: (Post Data: phone = 0000000)
AttributeError at /profile/
'QuerySet' object has no attribute '_meta'
Thank you!
Found myself in similar situation and I was able to solve as below.Hope it helps.
def update(self, instance, validated_data):
user_data = validated_data.pop('user')
user_serializer = UserSerializer()
super(self.__class__, self).update(instance,validated_data)
super(UserSerializer,user_serializer).update(instance.user,user_data)
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With