Python 从django haystack序列化搜索查询结果时如何包含外键字段
在谷歌搜索了很多之后,我似乎找不到解决这个问题的方法: 我已经创建了一个新的端点,用于从我的产品索引中搜索项目 使用Django oscar和Django oscar api,以下是模型:Python 从django haystack序列化搜索查询结果时如何包含外键字段,python,django,
elasticsearch,django-haystack,django-oscar,Python,Django,
elasticsearch,Django Haystack,Django Oscar,在谷歌搜索了很多之后,我似乎找不到解决这个问题的方法: 我已经创建了一个新的端点,用于从我的产品索引中搜索项目 使用Django oscar和Django oscar api,以下是模型: class Product(AbstractProduct): title = models.TextField(blank = True) class ProductImage(AbstractProductImage): product = models.ForeignKey('catal
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)
视图.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
序列化程序.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"
}]
另一件事,由于给定产品可能有多个图像,我还想返回第一个图像,其值为1。Try
images=product.ProductImageSerializer(source='productImageSet',many=True,required=False)
因为除非指定,否则DRF不会自动提供反向关系。@shad0w_wa1k3r,感谢您的回复,但我通过创建包含图像的索引解决了这个问题。这样我就可以像引用其他字段一样引用图像