我正在使用Django Rest Framework来创建我自己的restful API,但是我收到了上面的错误,我不知道它来自哪里.我已经阅读了有关此错误的其他帖子,但不幸的是他们没有太多帮助,所以如果有人能指出我哪里出错了,我将不胜感激.当我在我的模型中创建一个AutoField时,它开始发生,它在Animal模型中标记,而不在Doctor中.
我的models.py:
# Create your models here.
class Doctor(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
def __unicode__(self):
return self.id
class Animal(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
gender = models.CharField(max_length=10, choices=GENDER)
breed = models.CharField(max_length=200,)
adoption = models.BooleanField(default=False)
vaccines = models.CharField(max_length=20, choices=VACCINES)
doctor = models.ForeignKey(Doctor, null=True)
def __unicode__(self):
return self.id
serialisers.py:
class DoctorSerealiser(serializers.HyperlinkedModelSerializer):
class Meta:
model = Doctor
fields = ('id' , 'name')
class AnimalSerialiser(serializers.HyperlinkedModelSerializer):
# doctor = DoctorSerealiser(read_only=True)
class Meta:
model = Animal
fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')
views.py
class AnimalList(viewsets.ModelViewSet):
queryset = Animal.objects.all()
serializer_class = AnimalSerialiser
class DoctorDetail(viewsets.ModelViewSet):
queryset = Doctor.objects.all()
serializer_class = DoctorSerealiser
最佳答案 问题出在医生和动物的__unicode__方法中.您正在返回一个int的id,但此方法会检测str / buffer.将其更改为:
def __unicode__(self):
return str(self.id)