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

时间:2016-03-31 14:22:37

标签: python django django-rest-framework

我正在使用'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

感谢您的帮助。

3 个答案:

答案 0 :(得分:5)

您需要修改doctor字段名称才能成为正确的案例:

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

Doctor大写错误。

答案 1 :(得分:1)

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

  

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

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

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


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

答案 2 :(得分:1)

以上答案已经解决了这个特定问题。对我来说,我看到这个错误的原因完全不同,我在 fields 列表中的属性 id 后面缺少一个逗号,所以我收到了关于 name 的错误。

class SomeSerializer(serializers.ModelSerializer):
    class Meta:
        model = SomeModel
        fields = (
                  'id' # missed a comma here
                  'name'
                 )