Attribute error when attempting to get a value for

2019-06-26 02:23发布

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'.

1条回答
我想做一个坏孩纸
2楼-- · 2019-06-26 03:08

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 access queryset.user when it should be accessing visitor.user, so you need to tell the serializer that there are multiple objects (instead of a single one) by passing many=True.

查看更多
登录 后发表回答