Answer the question
In order to leave comments, you need to log in
Why does Django rest framework display the internal serializer incorrectly?
Actually the problem is that in the view I get the "relationship" field instead of the internal serializer.
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='User', null=True, blank=True)
first_name = models.CharField('First name', max_length=50)
last_name = models.CharField('Last name', max_length=50)
phone_number = models.CharField('Phone number', max_length=15)
activated = models.DateTimeField('Activated')
def __str__(self):
return f'<Profile {self.first_name.title()} {self.last_name.title()}>'
from rest_framework import serializers
from .models import Profile
from django.contrib.auth.models import User
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
fields = ('id', 'first_name', 'last_name', 'phone_number')
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('id', 'email', 'username', 'profile')
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from .serializers import UserSerializer
from .models import Profile
class UserViews(APIView):
def get(self, request, format=None):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
{
"data": [
{
"type": "UserViews",
"id": "1",
"attributes": {
"email": "",
"username": "admin",
"profile": {
"id": 1,
"first_name": "name1",
"last_name": "name2",
"phone_number": "+79999999999",
}
},
}
]
}
{
"data": [
{
"type": "UserViews",
"id": "1",
"attributes": {
"email": "",
"username": "admin"
},
"relationships": {
"profile": {
"data": {
"type": "Profile",
"id": "1"
}
}
}
}
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question