Django 'QuerySet' object has no attribute

Viewed 20

With this model:

class Batch(models.Model):
    product = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    stock = models.IntegerField()
    expiration = models.DateField()

This view:

@api_view(['GET'])
def getByProduct(request, product_name, format=None):

    try:
        batches = Batch.objects.filter(product=product_name)
    except Batch.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    
    serializer = BatchSerializer(batches)
    return Response(serializer.data, status=status.HTTP_200_OK)

And this URL:

path('get_by_product/<str:product_name>/', views.getByProduct),

I get the following error when running this:

http://127.0.0.1:8000/get_by_product/Potatoes/


Got AttributeError when attempting to get a value for field `product` on serializer `BatchSerializer`.
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 'product'.

However if I force a different error I get this:

Cannot resolve keyword 'many' into field. Choices are: created, expiration, history, id, product, stock

I cannot .get() as that query expects many batches with the same property "product".

Edit: This happens with any field, e.g.: batches = Batch.objects.filter(pk=1) Still returns the same error saying that product did not match any attribute, although it is not used anywhere. Maybe something is cached? I have no pending makemigrations/migrate

1 Answers

Solved! I was lacking many=True in the serializer:

serializer = BatchSerializer(batches, many=True)
Related