python - 删除 django 搜索中的重复结果
问题描述
我希望你很好。有谁知道如何删除搜索结果中的重复项?例如,如果我搜索“Louis”。我得到了 4 个重复的结果。有什么办法可以获得独特的结果吗?提前致谢。
用户/views.py
#search profile
@method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch")
class UserProfileResultsView(ListView):
model = UserProfile
template_name = 'search_results_user.html'
def get_queryset(self): # new
query = self.request.GET.get('q')
object_list = UserProfile.objects.filter(
Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) | Q(mealtrend__name__icontains=query) | Q(pricetrend__name__icontains=query) | Q(speedtrend__name__icontains=query)| Q(strengthtrend__name__icontains=query) | Q(wellnesstrend__name__icontains=query)
)
return object_list
模板/search_result_user.html
{% for userprofile in object_list %}
<a href="{% url 'user:user_public_cookwall' slug=userprofile.user.userprofile.slug %}" class="search_user_link">{{ userprofile.user.username }}</a>
{% endfor %}
解决方案
要从查询结果中消除重复行,请使用 Django 提供的 distinct() 方法。
不同的(*字段)
返回在其 SQL 查询中使用 SELECT DISTINCT 的新 QuerySet。这消除了查询结果中的重复行。
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#distinct
您可以按如下方式使用它:
object_list = UserProfile.objects.filter(...).distinct()
推荐阅读
- mysql - 如何修复 InnoDB 损坏的数据结构?
- android - 当数据按模型类在回收站视图中获取 firebase 数据库时,错误应用程序崩溃
- c# - C#/Unity Time.deltaTime 使相机跟随跳跃
- tensorflow - 具有多个输出模型的 Keras 自定义损失函数
- svg - 使用 SVG 作为嵌入式代码是否存在安全问题
- gremlin - 如何在 AWS SageMaker 上获取 gremlin python 客户端的版本
- octobercms - 将构建器制作的插件移动到另一个项目 - 十月 CMS
- entity-framework-6 - 如何在不获取 FirstChance IndexOutofRangeException 的情况下在 EF 业务对象中包含 [NotMapped] 属性?
- python - N体模拟python
- javascript - 内容渲染长文本