user3395936
user3395936

Reputation: 681

coercing to Unicode: need string or buffer, int found - Django Rest Framework

I am using Django Rest Framework to make my own restful API, but I am getting the error above, and I am not sure where it is coming from. I have read other posts on SO about this error but unfortunately they weren't much help, so would appreciate if someone could point out where I am going wrong. It started happening when I made id in my models an AutoField, and it flags in Animal model and not in 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

Upvotes: 3

Views: 5389

Answers (1)

ilse2005
ilse2005

Reputation: 11439

The problem is in the __unicode__ method of Doctor and Animal. You are returning the id which is a int, but this method excpects a str/buffer. Change it to:

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

Upvotes: 8

Related Questions