尝试获取字段值时出现属性错误 [英] Attribute error when attempting to get a value for field

查看:1057
本文介绍了尝试获取字段值时出现属性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django休息框架,我正在尝试使用的序列化器是创建错误。我正在尝试像 https://gist.github.com/anonymous/7463dce5b0bfcf9b6767 但我仍然收到错误。模型是

  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()
返回访问者

def __str __(self)
return self.user.username

,默认的用户类和序列化程序是



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

我收到这个错误



得到AttributeError当尝试在序列化程序 VisitorSerializer 上获取字段用户的值。
序列化程序字段可能命名不正确,与 QuerySet 实例上的任何属性或键不匹配。
原始异常文本是:'QuerySet'对象没有属性'user'。

解决方案

问题是你在没有设置许多标志的情况下,将一个查询器传递到序列化程序中。该错误告诉您,当它应该访问 visitor.user 时,串行器尝试访问 queryset.user 所以你需要通过传递 many = True 来告诉序列化器有多个对象(而不是一个对象)。


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

这篇关于尝试获取字段值时出现属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆