简体   繁体   English

Django 'QuerySet' object 没有属性

[英]Django 'QuerySet' object has no attribute

With this model:使用此 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:而这个 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".我cannot.get() 因为该查询需要许多具有相同属性“产品”的批次。

Edit: This happens with any field, eg: 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.编辑:任何字段都会发生这种情况,例如: batches = Batch.objects.filter(pk=1) 仍然返回相同的错误,指出产品不匹配任何属性,尽管它没有在任何地方使用。 Maybe something is cached?也许有些东西被缓存了? I have no pending makemigrations/migrate我没有待处理的 makemigrations/migrate

Solved!解决了! I was lacking many=True in the serializer:我在序列化程序中缺少 many=True :

serializer = BatchSerializer(batches, many=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM