Attribute error when trying to get value for a field
I am working with django rest framework and the serializer I am trying to use is throwing errors. I'm trying to do something like https://gist.github.com/anonymous/7463dce5b0bfcf9b6767 , but I still get the error. model
class Visitor(models.Model):
user = models.OneToOneField(User)
check_ins = models.IntegerField(default=0)
@classmethod
def create(cls, username, email, password):
user = User.objects.create_user(username, email, password)
visitor = cls(user=user)
visitor.save()
return visitor
def __str__(self):
return self.user.username
and custom default class and serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields = ('username')
class VisitorSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model=Visitor
fields = ('id','check_ins','user')
I am getting this error
Get AttributeError when trying to get a value for a field user
in serializer VisitorSerializer
. The serializer field may be named incorrectly and does not match an attribute or key on the instance QuerySet
. Source text for exceptions: The QuerySet object does not have a 'user' attribute.
source to share
The problem is that you are passing the request to your serializer without setting the flag many
. The error tells you that the serializer is trying to access queryset.user
when it should visitor.user
, so you need to tell the serializer that there are multiple objects (instead of one) by passing many=True
.
source to share