我有四个引用CustomUser表的模型。
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
...
class Question(models.Model):
question = models.CharField(max_length=140)
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
answer = models.CharField(max_length=70)
class Response(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='responses')
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
每个问题都有多个答案,但每个用户只能为每个问题选择一个答案。
每个用户可以回答多个问题。
我有一个ViewSet,经身份验证的用户可以访问该ViewSet,该ViewSet应该返回具有与他们相同的答案的用户列表。
serializer_class = serializers.ProfileSerializer
def get_queryset(self):
user_answers = qmodels.Answer.objects.filter(response__user=self.request.user)
return models.Profile.objects.prefetch_related(
Prefetch(
'user__responses',
queryset=qmodels.Response.objects.filter(answer__in=user_answers),
to_attr='common_answers'
)
)
class ProfileSerializer(serializers.ModelSerializer):
common_answers = ResponseSerializer(many=True)
但是,出现以下错误:
Got AttributeError when attempting to get a value for field `common_answers` on serializer `ProfileSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Profile` instance.
Original exception text was: 'Profile' object has no attribute 'common_answers'.
我在prefetch_related
之后添加了打印件,它可以正确显示基本记录,但是没有common_answers
字段