I'm working with the django rest framework and the serializer I'm trying to use is creating errors. I'm trying to do something like https://gist.github.com/anonymous/7463dce5b0bfcf9b6767 but I still get the error. the models are
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 the default user class and the serializers are
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 get this error
Got AttributeError when attempting to get a value for field user
on serializer VisitorSerializer
.
The serializer field might be named incorrectly and not match any attribute or key on the QuerySet
instance.
Original exception text was: 'QuerySet' object has no attribute 'user'.
The issue is that you are passing a queryset into your serializer without setting the
many
flag. The error is telling you that the serializer is trying to accessqueryset.user
when it should be accessingvisitor.user
, so you need to tell the serializer that there are multiple objects (instead of a single one) by passingmany=True
.