I got an Exception
Got AttributeError when attempting to get a value for field weight
on serializer WeightHistorySerializer
.
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 'weight'.
When I tried to retrive data.
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)
If it change to
weight_history = WeightHistory.objects.get(user_id=user_id)
It returns only one row, But I want all the rows with given user_id. So, What should I do to get all list with given user_id.
'QuerySet' object has no attribute 'weight'.
Yes. QuerySet
is a Set
, a list of objects.
<QuerySet [<Object1>, <Object2>,..]>
And that list has no attribute weight
. Instead, the objects inside the QuerySet
has the attribute weight
.
weight_history = WeightHistory.objects.filter(user_id=user_id)
filter
returns a QuerySet
, a list of WeightHistory
objects with user_id=user_id
.
And you are trying to serialize the list as a single object.
Instead of this:
serializer = WeightHistorySerializer(weight_history)
Do this:
serializer = WeightHistorySerializer(weight_history, many=True)
many=True
tells the serializer that a list of objects being passed for serialization.
Moreover,
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
This doesn't throw an exception at all. filter
returns an empty QuerySet if no objects exist. <QuerySet []>
.
So the final code is:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With