【问题标题】:How to serialize an array of objects in Django如何在 Django 中序列化对象数组
【发布时间】: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


【解决方案1】:

如果要序列化多条记录,要么改用ListSerializer,要么将many=True传递给ModelSerializer的构造函数:

return Response(ProductSerializer(queryset, many=True).data)

【讨论】:

  • 这两种解决方案都不起作用。当我将序列化程序转换为 ListSerializer 时,会收到以下错误 AssertionError at /market: 'child' is a required argument. 如果我通过 many=True,则会收到以下错误 'StoreView' should either include a queryset` 属性,或覆盖 get_queryset() 方法。我确实找到了一种让它工作的方法,我现在正在编辑问题。
  • 其实我从这里得到了解决方案。我只需要在 get 函数之外定义查询集,然后我的函数就可以更改它。谢谢!
【解决方案2】:

感谢@yedpodtrzitko 的指导,我找到了答案。 我必须进行两项更改。

  1. 在函数外定义queryset
  2. 传递 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)

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2021-10-13
    • 1970-01-01
    • 2020-02-11
    • 2015-03-15
    • 2011-02-10
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多