我希望你身体健康。有人知道我如何删除搜索结果中的重复项吗?例如,如果我搜索";Louis";。我得到了4个重复的结果。有什么方法可以得到独特的结果吗?提前谢谢。
user/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
templates/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((方法。
不同(*字段(
返回在中使用SELECT DISTINCT的新QuerySet它的SQL查询。这将从查询结果中消除重复的行。
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#distinct
您可以按如下方式使用它:
object_list = UserProfile.objects.filter(...).distinct()