I have a Django back-end built with django_rest_framework
. I currently have an object that is a foreign key. When I make a API request to grab an object it displays the foreignkey id and only the id. I want it to display the entire object rather than just the id of the foriegnkey. Not sure how to do it because it did not really show how to do it in the documentation.
Here is the code:
Views page:
from users.models import Profile
from ..serializers import ProfileSerializer
from rest_framework import viewsets
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
lookup_field = 'user__username'
serializer_class = ProfileSerializer
There is a user foreign key referring to the user.
Urls:
from users.api.views.profileViews import ProfileViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'', ProfileViewSet, base_name='profile')
urlpatterns = router.urls
The serializer:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
'id',
'user',
'synapse',
'bio',
'profile_pic',
'facebook',
'twitter'
)
This is what it looks like:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 1,
"user": 3,
"bio": "software engineer",
"profile_pic": "http://127.0.0.1:8000/api/user/profile/profile_pics/allsum-logo-1.png",
"facebook": "http://www.facebook.com/",
"twitter": "http://www.twitter.com/"
}
]
2
Answers
You can create a
UserSerializer
and use it inProfileSerializer
like this(using as nested serializer):Use
depth=1
in yourMeta
class of serializer,