强制转换为Unicode:需要字符串或缓冲区,找到int - Django Rest Framework

时间:2016-04-01 12:58:16

标签: python django django-rest-framework

我正在使用Django Rest Framework创建我自己的restful API,但我收到上面的错误,而且我不确定它来自何处。我已经阅读了有关此错误的其他帖子,但不幸的是,他们没有多大帮助,所以如果有人能够指出我哪里出错了,我将不胜感激。当我在我的模型中使用AutoField ID时,它就开始发生了,它在Animal模型中标记,而不在Doctor标记。

my 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

1 个答案:

答案 0 :(得分:7)

问题在于医生和动物的__unicode__方法。您正在返回一个int的id,但此方法会检测str / buffer。将其更改为:

def __unicode__(self):
    return str(self.id)