django-无法按外键名筛选

guykilcj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(374)

所以,目前我这样做,你可以搜索用户,参加了一个偶数,通过一些过滤器是 first_name, last_name, username 当前错误为
要解包的值太多(应为2)
视图中的错误行:

makefilter = "user__"+searchfilter+"__contains="+searchinput

usersearch = TeamMembership.objects.filter(makefilter)

如何通过过滤器成功搜索?

我的观点.py:

def volunteer(request):
    ## init context
    context = {}
    ## Get filters if somes
    searchfilter = request.GET.get('filter', None)
    searchinput = request.GET.get('searchinput', None)
    ## Checks if filter is not none or null or empty
    if searchfilter != "" and searchfilter != None and searchinput != "" and searchinput != None:
        ## Great now check what filter is used
        ## Now strip the filters for whitespaces
        searchfilter.strip()
        searchinput.strip()
        ## This filter is for teams
        if searchfilter == "teamname":
            teamsearch = Team.objects.all().filter(name__contains=searchinput)
            context['teams'] = True
            context['search'] = teamsearch
        ## This filter is for users
        elif searchfilter == "first_name" or searchfilter == "last_name" or searchfilter == "username" or searchfilter == "phone":
            makefilter = "user__"+searchfilter+"__contains="+searchinput
            usersearch = TeamMembership.objects.filter(makefilter)
            context['users'] = True
            context['search'] = usersearch
    return render(request, 'volunteer/hqvolunteer.html', context)

我的模型我试图搜索的用户模型是标准django auth:

class TeamMembership(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    ingroup = models.BooleanField(default=False)
    leader = models.BooleanField(default=False)
    groupleader = models.BooleanField(default=False)
kse8i1jr

kse8i1jr1#

在这里,您只需要构造一个字符串,也许它的形状类似于python代码,但这并不是您将任意参数名传递给函数的方式。
这里可以使用关键字参数,并构造一个字典,将键(参数的名称)Map到值(应该与该参数对应的值),如:

some_dict = { "user__"+searchfilter+"__contains": searchinput}

usersearch = TeamMembership.objects.filter(**some_dict)

万一 search_filter 例如 'email' ,和 searchinput 存在 'bar' ,则会导致 some_dict 存在 { 'user__email__contains': 'bar' } ,并呼叫:

TeamMembership.objects.filter(**{ 'user__email__contains': 'bar' })

相当于:

TeamMembership.objects.filter(user__email__contains='bar')

如果要筛选多个项,可以构造具有多个键的字典。但是请注意,键(如参数名)不能冲突(使用两次或两次以上相同的命名参数调用函数)。
此外,请注意 User 模型包含(散列)密码和其他敏感数据,您可能希望避免对某些字段进行过滤,因为可以使用此机制从系统中破解数据。

相关问题