在Django Rest框架中获取外键字段

时间:2018-08-21 03:26:14

标签: django django-rest-framework

访问我的API终结点,我得到这样的信息:

{
    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)"
}

我想做的是在此端点上拥有场所name和其他字段,而不是到另一个端点的URL。这可能吗?像这样:

{
    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视图)

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 个答案:

答案 0 :(得分:0)

使用 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')


参考
1. Serializer's source argument
2. ModelSerializer class