[英]AttributeError: 'QuerySet' object has no attribute 'category'
I am using DRF to get and create data from and to the API.我正在使用 DRF 从 API 获取和创建数据。 I was struggling with a model Question
and a attribute category
which is a model too.我正在努力解决一个 model Question
和一个属性category
,它也是一个 model。 So in order to create and read data I had to implement this question's answer method.因此,为了创建和读取数据,我必须实现这个问题的回答方法。 Therefore, whenever I create a question, its category is an integer but when I read it, is an object.因此,每当我创建一个问题时,它的类别是 integer,但当我阅读它时,它的类别是 object。
Whenever I use the default API route I can create and read the data, but I am getting the following error whenever I write a different route:每当我使用默认的 API 路由时,我都可以创建和读取数据,但是每当我编写不同的路由时都会出现以下错误:
AttributeError: Got AttributeError when attempting to get a value for field
category
on serializerQuestionSerializer
. AttributeError:尝试在序列化程序QuestionSerializer
上获取字段category
的值时出现 AttributeError。 The serializer field might be named incorrectly and not match any attribute or key on theQuerySet
instance.序列化程序字段可能命名不正确,并且与QuerySet
实例上的任何属性或键都不匹配。 Original exception text was: 'QuerySet' object has no attribute 'category'.原始异常文本为:'QuerySet' object 没有属性 'category'。
This is my custom code, where something is wrong...:这是我的自定义代码,哪里出了问题……:
class UserQuestions(APIView):
permission_classes = [permissions.IsAuthenticated]
def get(self, request, *args, **kwargs):
questions = Question.objects.filter(created_by=request.user.id).all()
data = QuestionSerializer(questions).data
return Response({
'questions': data
})
Just in case, this is my answer's implementation:以防万一,这是我的答案的实现:
class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField):
def __init__(self, **kwargs):
self.serializer = kwargs.pop('serializer', None)
if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer):
raise TypeError('"serializer" no es una clase serializer válida')
super().__init__(**kwargs)
def use_pk_only_optimization(self):
return False if self.serializer else True
def to_representation(self, instance):
if self.serializer:
return self.serializer(instance, context=self.context).data
return super().to_representation(instance)
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class QuestionSerializer(serializers.ModelSerializer):
category = RelatedFieldAlternative(queryset=Category.objects.all(), serializer=CategorySerializer)
answers = AnswerSerializer(many=True, source='answer_set', allow_null=True, required=False)
created_by = UserSerializer(required=False)
def to_representation(self, instance): response = super().to_representation(instance) response['category'] = CategorySerializer(instance.category).data return response
class Meta:
model = Question
fields = '__all__'
And this is the Question
model:这是Question
model:
class Question(models.Model):
id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
question = models.CharField(max_length=1000)
...
So, what am I doing wrong?那么,我做错了什么?
First of all, you are passing multiple items to serializer so you should use many=True
.首先,您将多个项目传递给序列化程序,因此您应该使用many=True
。 So in your case, it will be所以在你的情况下,它将是
data = QuestionSerializer(questions, many=True).data
Second, you don't need relatedFieldAlternative .其次,您不需要relatedFieldAlternative 。 You can just use a nested serailizer.您可以只使用嵌套的 serailizer。
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class QuestionSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Question
fields = '__all__'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.