【发布时间】:2021-07-24 23:20:59
【问题描述】:
我有一个简单的搜索 api,它根据提供给搜索键盘的查询参数搜索数据库。
它工作正常,但它有一些问题。
例如,我有一个名为电视和家用电器的类别。它拥有 LG 扬声器和 LED 电视等产品。我有类别名称和产品名称的搜索查询参数。当我搜索电视时,扬声器产品出现在第一页,而电视产品出现在我不想要的第 5 页。这是因为,类别名称有电视和家庭。
我想要的是电视产品出现在第一页,而扬声器则出现在其他页面。为此,我必须优先考虑产品名称字段而不是类别名称。
怎么做?
{
id:1
category: TV and Home,
product: 1500 W Speakers
}
{
id:2
category: Tv and Home,
product: Led Tv 32"
}
如果我用电视搜索的话,我希望 id:2 先出现,id:1。
class PrdouctSearchAPIView(ListAPIView):
permission_classes = [AllowAny]
queryset = Product.objects.all()
print(queryset)
serializer_class = ProductSerializer
filter_backends = [SearchFilter,OrderingFilter]
search_fields = ['name','brand__name','collection__name','sub_category__name',
'description','variants__color','category__name']
pagination_class = CustomPagination
我的本地端点是:
http://127.0.0.1:8000/api/productsearch?search=tv
我的模特:
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
name = models.CharField(max_length=150,unique=True
【问题讨论】:
标签: django api django-rest-framework django-views query-parameters