gpt4 book ai didi

django-rest-framework - 原始异常文本为 : 'QuerySet' object has no attribute 'weight'

转载 作者:行者123 更新时间:2023-12-03 16:03:58 25 4
gpt4 key购买 nike

我有一个异常(exception)
尝试获取字段 weight 的值时出现 AttributeError关于序列化程序 WeightHistorySerializer .
序列化器字段可能命名不正确,并且与 QuerySet 上的任何属性或键都不匹配。实例。
原始异常文本是:'QuerySet' 对象没有属性 'weight'。
当我尝试检索数据时。

模型.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)

序列化程序.py
class WeightHistorySerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = WeightHistory
fields = (
'id',
'weight',
'user_id',
'created_at'
)
read_only_fields = ('id',)

View .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 的所有列表。

最佳答案

'QuerySet' object has no attribute 'weight'.

是的。 QuerySetSet , 对象列表。
<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)

关于django-rest-framework - 原始异常文本为 : 'QuerySet' object has no attribute 'weight' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55041434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com