我有一个例外
尝试在序列化程序weight
上获取字段WeightHistorySerializer
的值时,出现 Got AttributeError。
序列化程序字段的名称可能不正确,并且与QuerySet
实例上的任何属性或键都不匹配。
原始异常文本为:'QuerySet'对象没有属性'weight'。
当我尝试检索数据时。
models.py
class WeightHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
weight = models.FloatField(null=False, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
serializers.py
class WeightHistorySerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = WeightHistory
fields = (
'id',
'weight',
'user_id',
'created_at'
)
read_only_fields = ('id',)
views.py
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
如果更改为
weight_history = WeightHistory.objects.get(user_id=user_id)
它仅返回一行,但是我希望所有行都具有给定的user_id。因此,我该怎么做才能获得具有给定user_id的所有列表。
答案 0 :(得分:0)
'QuerySet' object has no attribute 'weight'.
是的。 QuerySet
是Set
,是对象列表。
<QuerySet [<Object1>, <Object2>,..]>
并且该列表没有属性weight
。相反,QuerySet
内部的对象具有属性weight
。
weight_history = WeightHistory.objects.filter(user_id=user_id)
filter
返回QuerySet
,是WeightHistory
对象的列表,其中包含user_id=user_id
。
您正在尝试将列表序列化为单个对象。
代替此:
serializer = WeightHistorySerializer(weight_history)
执行以下操作:
serializer = WeightHistorySerializer(weight_history, many=True)
many=True
告诉序列化程序要传递序列化对象的列表。
此外,
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
这根本不会引发异常。如果没有对象,则filter
返回一个空的QuerySet。 <QuerySet []>
。
所以最终的代码是:
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
weight_history = WeightHistory.objects.filter(user_id=user_id)
if weight_history.count()<1:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history, many=True)
return Response(serializer.data)
答案 1 :(得分:0)
views.py
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.get(user_id=user_id) #get
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
使用 get
而不是 filter
它会解决你的错误