Get foreign key fields in django rest framework

Get foreign key fields in django rest framework



Accessing my API endpoint I get something like this:



place: "https://example.com/api/places/998/?format=json",
item: "Stone Fruit Salad",
description: "greens • fennel • cucumber"
,

place: "https://example.com/api/places/999/?format=json",
item: "Elote",
description: "sweet corn • raddish • goat milk feta • pepita • chipotle yogurt dressing • (can be made vegan)"



What I'd like to do is have the place name and other fields available from this endpoint, instead of the the URL to another endpoint. Is this possible? Something like this:


name



place_name: "Place 1",
place_website: "example.com",
item: "Stone Fruit Salad",
description: "greens • fennel • cucumber"
,

place_name: "Place 2",
place_website: "example.com",
item: "Elote",
description: "sweet corn • raddish • goat milk feta • pepita • chipotle yogurt dressing • (can be made vegan)"



serializer.py


from ..models import MenuItem
from rest_framework import serializers


class MenuItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MenuItem
fields = ('place','item','description')



views.py (api views)


from ..models import MenuItem
from rest_framework import viewsets
from .serializers import MenuItemSerializer


class MenuItemViewSet(viewsets.ModelViewSet):
queryset = MenuItem.objects.all()
serializer_class = MenuItemSerializer




1 Answer
1



Use ModelSerializer instead of HyperlinkedModelSerializer as,


ModelSerializer


HyperlinkedModelSerializer


class MenuItemSerializer(serializers.ModelSerializer):
place_name = serializers.CharField(source='place.name')
place_website = serializers.CharField(source='place.website')


class Meta:
model = MenuItem
fields = ('place_name', 'place_website', 'item', 'description')




Reference

1. Serializer's source argument

2. ModelSerializer class


source


ModelSerializer





@smilebomb Added few references related to the answer. Take a look :)
– JPG
Aug 21 at 3:43






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

ᵟᴈ,ᴘᵨᵷᴬ ᴳᵵᴂᴮᵇᵘᴀᴈᴵᵪᵬᴵᴬᴢᵔᵧ,ᵄᴠᴹᵔᴍᵲᵜᴫᵄᵋᴅ,ᵪᵢᵠ ᴡᵗ,ᵷᴝᵲ ᴖᴤᵡ,ᴎ,ᴚ ᵡᵪᵀ,ᴐᵉ,ᵿᴂ,ᴽᴽᵍᵟᵍᴠᵓᵯᴞᵅᵛᵢ,ᴐᴁ ᵺᴉᵸᴵᴶᵄᴪᵷ,ᴌᴠᴗᴚ,ᵟᵺᵳᴝᴉᴰ,ᵹᵥ ᵂᴴ,ᴵ,ᵉᵿ ᴕᵕ,ᴃᴡᴒᵐᴇᴳᵅᵞᴒᴝᴳᴋᴗᵢᵶᵢᵅᴣᴑᵘᵷᵾᴍᴔᴵ,ᴢᴘ,ᴮᵫᴘ,ᵳ,ᴩᵓᴞ