Django Rest Framework - 未正确生成嵌套对象

时间:2017-06-11 11:29:37

标签: python django rest django-rest-framework

我正在尝试在Django Rest Framework中实现简单的api。

我在 models.py

中有以下模型
class Entry(BaseModel):
    company_name = models.CharField(max_length=256, null=True, blank=True)
    first_name = models.CharField(null=True, default=None, max_length=32)
    last_name = models.CharField(null=True, default=None, max_length=32)
    code = models.CharField(null=True, default=None, max_length=12)


    class Meta:
        db_table = 'entry'

    class Admin(admin.ModelAdmin):
        list_display = ('company_name', 'code')
        list_display_links = ('company_name', )
        ordering = ('-created',)


class EntryContactData(BaseModel):
    entry = models.ForeignKey(Entry, related_name='contact')
    email = models.CharField(max_length=256, null=True, blank=True)
    website = models.CharField(max_length=64, null=True, blank=True)
    phone = models.CharField(max_length=64, null=True, blank=True)

我的API serializers.py:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from core.models import Entry, EntryContactData


class EntryContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = EntryContactData
        fields = ('uuid', 'email', 'website', 'phone')


class EntrySerializer(serializers.ModelSerializer):
    contact = EntryContactSerializer(many=False, read_only=True)

    class Meta:
        model = Entry
        fields = ('uuid', 'company_name', 'first_name', 'last_name', 'contact')

我的API观点:

from core.models import Entry
from .serializers import EntrySerializer


class EntryViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving users.
    """
    queryset = Entry.objects.all()

    def retrieve(self, request, pk=None):
        queryset = Entry.objects.all()
        entry = get_object_or_404(queryset, code=pk)
        serializer = EntrySerializer(entry, context={'request': request})
        return Response(serializer.data)

当我想检索单个条目时,其contact字段为空:

{
    "uuid": "e6818508-a172-44e1-b927-3c087d2f9773",
    "company_name": "COMPANY NAME",
    "first_name": "FIRSTNAME",
    "last_name": "LASTTNAME",
    "contact": {}
}

因此它不包含EntryContactSerializer

中定义的任何字段

我做错了什么?如何强制它返回序列化程序中包含的所有字段?谢谢你们。

1 个答案:

答案 0 :(得分:0)

尝试在EntrySerializer中设置many=True,并为序列化程序提供source属性,

class EntrySerializer(serializers.ModelSerializer): 
    contact = EntryContactSerializer(source='contact', many=True, read_only=True) 
    class Meta: 
        model = Entry 
        fields = ('uuid', 'company_name', 'first_name', 'last_name', 'contact')