在大量搜索之后,我似乎无法找到解决方案: 我创建了一个新的端点,用于从“产品索引”中搜索商品
将Django oscar与django oscar api结合使用,以下是这些模型:
class Product(AbstractProduct):
title = models.TextField(blank = True)
class ProductImage(AbstractProductImage):
product = models.ForeignKey('catalogue.Product', on_delete=models.CASCADE)
display_order = models.PositiveIntegerField()
remote_image = models.URLField(blank=True)
views.py
class ItemSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = ItemSearchSerializer
def get_queryset(self):
request = self.request
queryset = EmptySearchQuerySet()
if request.GET.get('q', ''):
query = request.GET.get('q', '')
queryset = SearchQuerySet().filter(content=query)
return queryset
Serializers.py
from oscarapi.serializers import product
class ItemSearchSerializer(serializers.ModelSerializer):
text = serializers.CharField()
title = serializers.CharField()
price = serializers.HyperlinkedIdentityField(view_name='product-price')
image = product.ProductImageSerializer(many=True, required=False)
class Meta():
model = Product
fields = ('image', 'price', 'text', 'title')
当我用localhost:8000/api/search/?q=bmw
击中端点时,似乎适用于所有其他字段,但不返回图像,这是示例:
[
{
"image": null,
"price": "http://localhost:8000/api/products/2339/price/",
"text": "2339\nBMW 316 SE Automatic",
"title": "BMW 316 SE Automatic"
},
{
"image": null,
"price": "http://localhost:8000/api/products/0029/price/",
"text": "0029\nBmw 330d\nLoverly car in excellent condition",
"title": "Bmw 330d"
}]
另一件事,因为给定产品可能有几张图像,我也想只返回第一张图像,该图像的display_order
值为1。