use*_*936 4 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)
Run Code Online (Sandbox Code Playgroud)
我的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')
Run Code Online (Sandbox Code Playgroud)
我的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
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助。
hat*_*gic 18
上面的答案已经解决了这个具体问题。fields对我来说,我看到这个错误的原因完全不同,我在list 中的一个 attribute 之后缺少一个逗号id,所以我得到了关于 的错误name。
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = (
'id' # missed a comma here
'name'
)
Run Code Online (Sandbox Code Playgroud)
您需要将doctor字段名称修改为适当的情况:
fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')
Run Code Online (Sandbox Code Playgroud)
Doctor 目前是错误的大写。
无论您将在 Serializer 中定义什么字段,您都需要将其放在元类字段中。如果你不提到你会得到错误。
builtins.AssertionError AssertionError:在序列化程序 ABCSerializer 上声明了字段“abc”,但尚未包含在“字段”选项中。
因此,在您的情况下,您已在序列化程序中定义了医生字段,因此您的元字段应具有此医生字段。它区分大小写。所以你将不得不使用医生而不是医生。
class AnimalSerialiser(serializers.HyperlinkedModelSerializer):
doctor = DoctorSerealiser()
class Meta:
model = Animal
fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7737 次 |
| 最近记录: |