尝试获取序列化器“ xxx”上字段“ xxx”的值时出现AttributeError

时间:2019-04-27 16:23:39

标签: python django django-rest-framework

嗨,我正在尝试访问以下网址:http://192.168.1.5:8000/api/parents/,但出现此错误:

AttributeError at /api/parents/
Got AttributeError when attempting to get a value for field `nom` on serializer `ParentSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Adresse` instance.
Original exception text was: 'Adresse' object has no attribute 'nom'.

上周工作正常,但我不记得我到底做了什么更改

这是我的文件models.py:

class Adresse(models.Model):
 id=models.AutoField(primary_key=True)
 ville=models.CharField(max_length=20)
 region=models.CharField(max_length=20)
 quartier=models.CharField(max_length=20)
 codePostal=models.IntegerField()
 rue=models.CharField(max_length=50)


 def __str__(self):
     return 'Ville :{} ,Région: {},Quartier : {},Code Postal : {},Rue :  {} .'.format(self.ville,self.region,self.quartier,self.codePostal,self.rue)



class Ecole(models.Model):
 NIVEAU=(('Maternelle','Maternelle'),('Primaire','Primaire'), ('College','Collège'),('Lycee','Lycée'))
 id=models.AutoField(primary_key=True)
 niveau=models.CharField(max_length=10,choices=NIVEAU,default='')
 nom=models.CharField(max_length=30,unique=True)
 adresse=models.ForeignKey(Adresse,on_delete=models.CASCADE,default='')

 def __str__(self):
    return '{}'.format(self.nom)


class Etudiant(models.Model):

 id=models.AutoField(primary_key=True)
 nom=models.CharField(max_length=20)
 prenom=models.CharField(max_length=20)
 email=models.EmailField()
 tel=models.CharField(max_length=10)
 adresse=models.ForeignKey(Adresse,on_delete=models.CASCADE,default='')
 ecole=models.ForeignKey(Ecole,on_delete=models.CASCADE,default='')

 def __str__(self):
    return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom)


class Parent(models.Model):
 id=models.AutoField(primary_key=True)
 nom=models.CharField(max_length=20)
 prenom=models.CharField(max_length=20)
 email=models.EmailField()
 tel=models.CharField(max_length=10)
 etudiant=models.ForeignKey(Etudiant,on_delete=models.CASCADE,default='')

 def __str__(self):
    return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

实际上找到了我犯的错误,我写道:

class ParentViewSet(viewsets.ModelViewSet):
 queryset=Adresse.objects.all()
 serializer_class=ParentSerializer

而不是:

class ParentViewSet(viewsets.ModelViewSet):
 queryset=Parent.objects.all()
 serializer_class=ParentSerializer