自定义分页Django Rest Framework中的错误

时间:2019-10-29 12:57:17

标签: python django django-rest-framework

我在项目中使用APIView,并且自定义分页也正在工作,但是它多次显示相同的元素。到目前为止,我在这里已经尝试过了。

views.py

class ProductByBrand(APIView):
    pagination_class = LimitOffsetPaginationUpperBond

    @property
    def paginator(self):
        if not hasattr(self, '_paginator'):
            if self.pagination_class is None:
                self._paginator = None
            else:
                self._paginator = self.pagination_class()
        return self._paginator

    def paginate_queryset(self, queryset):
        if self.paginator is None:
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self, ctx):
        assert self.paginator is not None
        return self.paginator.get_paginated_response(ctx)

    def get(self, request, slug, brand, format='json'):

        pid = Category.objects.get(slug=slug)
        data = Category.objects.filter(parent_id=pid)
        data_categories = []
        for category in data:
            data_categories += Category.objects.filter(parent_id=category.id)
        all_product = []
        for data_category in data_categories:
            all_product += Product.objects.filter(category_id=data_category.id, brand=brand)

        print(all_product)
        ctx = []
        for product in all_product:
            str = settings.MEDIA_URL + product.image.name
            ctx.append({
                'id': product.id,
                'name': product.name,
                'slug': product.slug,
                'brand': product.brand_id,
                'image': str,
                'price': product.price,
                'rating': product.rating,
                'discount': product.discount
            })
        queryset = Product.objects.all()
        page = self.paginate_queryset(queryset)
        if page is not None:
            return self.get_paginated_response(ctx)

更准确地说,我在“类别”部分中选择品牌,以过滤与该类别相关的产品。例如: 我有两个产品

enter image description here

electronics类别可以看出,它有两个与品牌相关的产品,其ID为 3 。在这种情况下,我只有两个产品而不是四个。但是从上图可以看到,它给了我4个相同的产品,而不是2个。我该如何解决这个问题?预先感谢!

1 个答案:

答案 0 :(得分:0)

这将有助于查看更多数据数据,但是由于两个conda create -n keras-gpu pip python=3.6 conda activate keras-gpu pip install tensorflow-gpu==1.13.1 pip install keras==2.2.4 循环,您可能会得到重复数据。这些可以是直接的ORM查询,例如:

for