在视图djang中过滤查询集问题

2024-04-26 23:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我提前道歉,因为我还是django的新手,我继承了这个项目。你知道吗

我现在有这个视图.py你知道吗

def home(request):
    if request.user.is_authenticated():
        location = request.GET.get('location', request.user.profile.location)
        users = User.objects.filter(profile__location=location) 
        print (users)
        matches = Match.objects.get_matches_with_percent(request.user)
        print (matches)

我从“matches=”like this from the print(matches)[[<User: lucy>, '79.00%'], [<User: newuser>, '70.71%'],......中的匹配应用程序中获得一个用户列表

我从“users=”like this from print(users)[<User: jonsnow>, <User: newuser>]......得到一个用户列表

如何将匹配项筛选到通过的用户,我尝试在“matches=”how i got this error“'list'object has no attribute'filter'”的末尾添加一个.filter(User=users)。你知道吗

我真的希望这有点道理,如果我在这里解释得很糟糕,我真的道歉,并提前感谢你的任何帮助。你知道吗


Tags: 用户fromgetobjectsrequestlocationfilterthis
2条回答

get_matches_with_percent不是django方法,而是模型管理器中的自定义方法。在网上搜索时,我假设this is your code,特别是你的方法。它不返回查询集,而是返回常规列表。如果希望能够过滤查询集,则必须更新该方法。你知道吗

你可以用列表来理解。他们速度很快,执行时间很短。下面应该可以做到这一点:

matches = [match for match in matches if match[0] in users]

user_ids = users.values_list('id', flat=True)
matches = [match for match in matches if match[0].id in user_ids]

相关问题 更多 >