【发布时间】:2021-05-16 14:14:25
【问题描述】:
我正在使用 Django 和 REST Framework,我正在尝试为我的一个视图创建一个 get 函数并遇到错误。基本想法是我正在创建一个可以有多个商店的市场。每个商店可以有许多产品。因此,我正在尝试查询一家商店中存在的所有产品。一旦我得到所有这些产品,我想将它发送到我的序列化程序,它最终会将它作为 JSON 对象返回。我已经能够使它适用于一个产品,但它不适用于一系列产品。
我的产品模型如下所示:
'''Product model to store the details of all the products'''
class Product(models.Model):
# Define the fields of the product model
name = models.CharField(max_length=100)
price = models.IntegerField(default=0)
quantity = models.IntegerField(default=0)
description = models.CharField(max_length=200, default='', null=True, blank=True)
image = models.ImageField(upload_to='uploads/images/products')
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model
store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1)
''' Filter functions for the product model '''
# Create a static method to retrieve all products from the database
@staticmethod
def get_all_products():
# Return all products
return Product.objects.all()
# Filter the data by store ID:
@staticmethod
def get_all_products_by_store(store_id):
# Check if store ID was passed
if store_id:
return Product.objects.filter(store=store_id)
我构建的产品序列化器如下:-
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
我创建的视图在下面
class StoreView(generics.ListAPIView):
"""Store view which returns the store data as a Json file.
"""
# Define class variables
serializer_class = StoreSerializer
# Manage a get request
def get(self, request):
# Get storeid for filtering from the page
store_id = request.GET.get('id')
if store_id:
queryset = Product.get_all_products_by_store(store_id)
# queryset = Product.get_all_products_by_store(store_id)[0]
else:
queryset = Product.get_all_products()
# queryset = Product.get_all_products()[0]
print("QUERYSET", queryset)
return Response(ProductSerializer(queryset).data)
上面的视图给了我以下错误
AttributeError at /market
Got AttributeError when attempting to get a value for field `name` on serializer `ProductSerializer`.
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 'name'.
如果改为queryset = Product.get_all_products_by_store(store_id),我使用它下面的行,我只选择第一个选项,然后我得到正确的 JSON 响应,但如果有多个产品,那么我无法序列化。如何让它发挥作用?
【问题讨论】:
-
get_all_products_by_category长什么样子? -
对不起,也像商店。我只是早些时候使用它,忘记更改。实际上,我会进行编辑。编辑:现已修复。
标签: python django django-rest-framework django-serializer