AssertionError:字段''在序列化服务器上 声明'',但未包含在'fields'选项中

问题描述 投票:3回答:2

我正在使用'Django Rest Framework',我正在尝试构建RestfulAPI。但是,当我运行我的应用程序时,我得到上述错误:AssertionError: The field 'doctor' was declared on serializer AnimalSerialiser, but has not been included in the 'fields' option.我不确定fields是什么,因此无法追查问题。

我的models.py:

from __future__ import unicode_literals

from django.db import models

# Create your models here.
class Doctor(models.Model):

    id= models.CharField(max_length=10, primary_key=True, unique=True)
    name = models.CharField(max_length=20)

    def __unicode__(self):
        return self.id

class Animal(models.Model):
    id = models.CharField(max_length=10, primary_key=True, unique=True)
    name = models.CharField(max_length=200)
    gender = models.CharField(max_length=10)
    breed = models.CharField(max_length=200)
    adoption = models.CharField(max_length=10)
    vaccines = models.CharField(max_length=20)
    doctor = models.ForeignKey(Doctor, null=True)

我的serialisers.py:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
from models import Animal, Doctor

class DoctorSerealiser(serializers.HyperlinkedModelSerializer):
    class Meta:
         model = Doctor
         fields = ('id' , 'name')


class AnimalSerialiser(serializers.HyperlinkedModelSerializer):
    doctor = DoctorSerealiser()


    class Meta:
        model = Animal
        fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'Doctor')

我的views.py:

from django.shortcuts import render

# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, generics

from cw.myStart.models import Animal
from cw.myStart.serializers import AnimalSerialiser, DoctorSerealiser
from models import Animal, Doctor

class AnimalList(viewsets.ModelViewSet):
    queryset = Animal.objects.all()
    serializer_class = AnimalSerialiser

class DoctorDetail(viewsets.ModelViewSet):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerealiser

谢谢你的帮助。

python django django-rest-framework
2个回答
5
投票

你需要修改你的doctor字段名称是正确的情况:

fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')

Doctor目前是错误的大写。


1
投票

无论您将在Serializer中定义哪个字段,都需要将其放在元类字段中。如果你没有提到,你将收到错误。

builtins.AssertionError AssertionError:字段'abc'在序列化程序ABCSerializer上声明,但未包含在'fields'选项中。

因此,在您的情况下,您已在序列化程序中定义了医生字段,因此元字段应具有此医生字段。它区分大小写。所以你必须使用医生而不是医生。

class AnimalSerialiser(serializers.HyperlinkedModelSerializer):
doctor = DoctorSerealiser()


class Meta:
    model = Animal
    fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')
© www.soinside.com 2019 - 2024. All rights reserved.