首页 > 解决方案 > 删除 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 %}

标签: pythondjango

解决方案


要从查询结果中消除重复行,请使用 Django 提供的 distinct() 方法。

不同的(*字段)

返回在其 SQL 查询中使用 SELECT DISTINCT 的新 QuerySet。这消除了查询结果中的重复行。

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#distinct

您可以按如下方式使用它:

object_list = UserProfile.objects.filter(...).distinct()

推荐阅读