【发布时间】:2021-04-13 13:48:56
【问题描述】:
我想通过搜索表单检索模型的对象,但为搜索分数添加另一列。我不确定如何使用 django-tables2 和 django-filter 来实现这一点。
将来,我希望用户能够使用 django-filter 来帮助过滤搜索结果。我可以从PeopleSearchListView 访问表单变量,但也许这是集成 django 表单以进行表单处理的更好方法?
到目前为止,我的想法是处理 get_queryset() 中的 get 请求,然后在将查询集发送到 PeopleTable 之前对其进行修改,但是向查询集中添加另一列似乎不是标准方法。
tables.py
class PeopleTable(tables.Table):
score = tables.Column()
class Meta:
model = People
template_name = 'app/bootstrap4.html'
exclude = ('id',)
sequence = ('score', '...')
views.py
class PeopleFilter(django_filters.FilterSet):
class Meta:
model = People
exclude = ('id',)
class PeopleSearchListView(SingleTableMixin, FilterView):
table_class = PeopleTable
model = People
template_name = 'app/people.html'
filterset_class = PeopleFilter
def get_queryset(self):
p = self.request.GET.get('check_this')
qs = People.objects.all()
####
# Run code to score users against "check_this".
# The scoring code I'm using is complex, so below is a simpler
# example.
# Modify queryset using output of scoring code?
####
for person in qs:
if person.first_name == 'Phil' and q == 'Hey!':
score = 1
else:
score = 0
return qs
urls.py
urlpatterns = [
...
path('search/', PeopleSearchListView.as_view(), name='search_test'),
... ]
models.py
class People(models.model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
编辑: 评分算法比上面的例子要复杂一些。在最终将每个得分行与搜索查询进行比较之前,它需要对 People 表中的所有行进行完整遍历以生成得分矩阵。这不是一次性的分数。例如:
def get_queryset(self):
all = []
for person in qs:
all.append(person.name)
# Do something complex with all,
# e.g., measure cosine distance between every person,
# and finally compare to the get request
scores = measure_cosine(all, self.request.GET.get('check_this'))
# We now have the scores for each person.
【问题讨论】:
-
如何计算分数?
-
@markwalker_ 评分算法有点简单。但我添加了一个评分 sn-p 的示例来提供帮助。重要的是模型中的每一行都有一个分数,我想在可过滤表中输出该行旁边的所有分数。
标签: python django django-queryset django-filter django-tables2