python - AssertionError : The field ' ' was declared on serializer ' ' ,,但尚未包含在 'fields'选项中

标签 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

谢谢你的帮助。

最佳答案

您需要修改doctor字段名称为适当的情况:

fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')
Doctor当前为大写错误。

关于python - AssertionError : The field ' ' was declared on serializer ' ' ,,但尚未包含在 'fields'选项中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336145/

相关文章:

python - 如何使用where子句在MySQL中插入多行

python - djangorest框架在create中动态设置外键

Django fixture 加载很慢

python - 测试经过身份验证的 django-rest-framework 路由时出现 405 错误

python - Django Rest Framework SerializerMethodField TypeError : "' RelatedManager' object does not support indexing"

python - Flask:具有自定义域名的 Heroku 会中断 session 吗?

python - 如何检查 Pandas 系列是否包含时间戳?

python - 如何在Django Rest Framework中获取xml格式

python - 使用字符串搜索列表

python - 我们可以用 Django 生成人口脚本吗?