如何序列化 Django 中的对象数组
How to serialize an array of objects in Django
我正在使用 Django 和 REST Framework,我正在尝试为我的一个视图创建一个 get 函数,运行 出现错误。基本思想是我正在创建一个可以有多个商店的市场。每个商店可以有很多产品。因此,我试图查询一家商店中存在的所有产品。一旦我得到所有这些产品,我想将它发送到我的序列化器,它最终将 return 它作为一个 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 响应,但如果有多个产品,那么我无法序列化.我如何让它发挥作用?
如果要序列化多个记录,请改用 ListSerializer
,或将 many=True
传递给 ModelSerializer
:
的构造函数
return Response(ProductSerializer(queryset, many=True).data)
感谢@yedpodtrzitko 的指导,我找到了答案。
我必须进行两项更改。
- 在函数外定义
queryset
- 将 many=True 传递给
ModelSerializer
的构造函数
class StoreView(generics.ListAPIView):
"""Store view which returns the store data as a Json file.
"""
# Define class variables
queryset = []
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)
else:
queryset = Product.get_all_products()
print("QUERYSET", queryset)
return Response(ProductSerializer(queryset, many = True).data)
我正在使用 Django 和 REST Framework,我正在尝试为我的一个视图创建一个 get 函数,运行 出现错误。基本思想是我正在创建一个可以有多个商店的市场。每个商店可以有很多产品。因此,我试图查询一家商店中存在的所有产品。一旦我得到所有这些产品,我想将它发送到我的序列化器,它最终将 return 它作为一个 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 响应,但如果有多个产品,那么我无法序列化.我如何让它发挥作用?
如果要序列化多个记录,请改用 ListSerializer
,或将 many=True
传递给 ModelSerializer
:
return Response(ProductSerializer(queryset, many=True).data)
感谢@yedpodtrzitko 的指导,我找到了答案。 我必须进行两项更改。
- 在函数外定义
queryset
- 将 many=True 传递给
ModelSerializer
的构造函数
class StoreView(generics.ListAPIView):
"""Store view which returns the store data as a Json file.
"""
# Define class variables
queryset = []
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)
else:
queryset = Product.get_all_products()
print("QUERYSET", queryset)
return Response(ProductSerializer(queryset, many = True).data)