I am using APIView
in my project and custom pagination also it is working but it shows same elements multiple time. Here I have tried so far.
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)
to be more precise I select brand in category section to filter the products related to that category. For example: I have two product
as it can be seen from electronics
category it has two products related to brand which id is 3 . In this case I have only two products not four. But it gives me 4 same product instead of 2 as you can see from the picture above. How can I solve this issue? Thanks in advance!
It would help to see more of what your data looks like, but you're probably getting duplicates because of the two for
loops. Those can be direct ORM queries something like this:
def get(self, request, slug, brand, format='json'):
pid = Category.objects.get(slug=slug)
data = Category.objects.filter(parent_id=pid)
data_categories = Category.objects.filter(parent__in=data)
all_product = Product.objects.filter(category__in=data_categories, brand=brand)
print(all_product)
ctx = []
for product in all_product:
[...]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.