请访问https://stackoverflow.com/questions/77300502/django-turn-off-on-pagination-for-one-filter-request/77300948#77300948

ioekq8ef  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(96)

正如标题中的问题所提到的,我有2个模型,1个产品和1个产品图像。我试图让产品列表沿着与相关的产品图片,

class Product(models.Model):
    title = models.CharField(max_length=200)
    details = models.TextField(null = True)
    slug = models.CharField(max_length=300, unique=True, null=True)
class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs')
    image = models.ImageField(upload_to='product_imgs/', null=True)

    def __str__(self):
        return self.image.url

我的观点为获取产品列表是,

def get_queryset(self):
        qs = super().get_queryset()
        if self.request.method == 'GET':
            if 'category' in self.request.GET:
                category = self.request.GET['category']
                category = models.ProductCategory.objects.get(id=category)
                qs = qs.filter(category=category)
            if 'owner' in self.request.GET:
                print('get_queryset Owner')
                owner = self.request.GET['owner']
                qs = qs.filter(owner=owner)
                if 'available' in self.request.GET:
                    available = self.request.GET['available'] == 'true'
                    qs = qs.filter(available=available)
            results = []
            for product in qs:
                images = models.ProductImages.objects.filter(product=product.id)
                results.append({'product': product, 'images': images})
        return JsonResponse({
            'status': 'success',
            'result': results,
        })

我得到一个错误,说
TypeError:Product类型的对象不是JSON可序列化的
在线
return JsonResponse({
还尝试了以下两种可能的解决方案,

results = []
            for product in qs:
                images = models.ProductImages.objects.filter(product = product.id)
                serialized_images = [{'url': img.image.url} for img in images]
                results.append({'product': product.id, 'images': serialized_images})
            serializer = serializers.ProductListSerializer(qs, many = True)
            response = {'products': serializer.data, 'product_image': results}

results = []
            for product in qs:
                images = models.ProductImages.objects.filter(product = product.id)
                serialized_product = {
                     'id': product.id,
                     'title': product.title,
                     'description': product.description,
                     ...
                }
                serialized_images = [{'url': img.image.url} for img in images]
                results.append({'product': serialized_product, 'images': serialized_images})
            return results

但我得到以下错误,

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/opt/homebrew/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/generics.py", line 239, in get
    return self.list(request, *args, **kwargs)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/mixins.py", line 40, in list
    page = self.paginate_queryset(queryset)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/generics.py", line 171, in paginate_queryset
    return self.paginator.paginate_queryset(queryset, self.request, view=self)
  File "/opt/homebrew/lib/python3.10/site-packages/rest_framework/pagination.py", line 204, in paginate_queryset
    self.page = paginator.page(page_number)
  File "/opt/homebrew/lib/python3.10/site-packages/django/core/paginator.py", line 77, in page
    return self._get_page(self.object_list[bottom:top], number, self)
TypeError: unhashable type: 'slice'

我找不到返回响应的解决方案,这是2种不同模型的组合。有没有人可以帮我解决这个问题?
PS:我不想在前端获得产品列表,然后进行网络调用/调用,以获得与它们相关联的图像。

pengsaosao

pengsaosao1#

我假设问题来自以下几行:

images = models.ProductImages.objects.filter(product=product.id)
results.append({'product': product, 'images': images})

然后:

return JsonResponse({
    'status': 'success',
    'result': results,
})

这里要做的是将ProductImages示例列表序列化为JSON响应中products键的值。
但是JsonResponse不知道怎么做。
你可以这样做:

results = []
for product in qs:
    images = models.ProductImages.objects.filter(product=product.id)
    serialized_product = {
        'id': product.id,
        'name': product.name,
    }
    serialized_images = [{'url': img.image.url} for img in images]
    
    results.append({'product': serialized_product, 'images': serialized_images})

相关问题