How can I chain Django's “in” and “iexact” queryset field lookups?

我是研究僧i 提交于 2019-12-03 11:45:01

问题


I have a list of names, e.g.:

name_list = ['Alpha', 'bEtA', 'omegA']

Currently I have the following queryset:

MyModel.objects.filter(name__in=name_list)

I would like to be able to filter the names in a case-insensitive fashion. My first thought was to use the iexact field lookup but it doesn't seem to work with in. How can I use the iexact with the in field lookup for my queryset? Or is there an alternate way to perform this query?


回答1:


Here's my solution, which uses Q objects instead:

name_list = ['Alpha', 'bEtA', 'omegA']
q_list = map(lambda n: Q(name__iexact=n), name_list)
q_list = reduce(lambda a, b: a | b, q_list)
MyModel.objects.filter(q_list)



回答2:


name_list = ['Alpha', 'bEtA', 'omegA']
results = MyModel.objects.none()
for name in name_list:
    results |= MyModel.objects.filter(name__iexact=name)

Ok I test it and it works :)



来源:https://stackoverflow.com/questions/14907525/how-can-i-chain-djangos-in-and-iexact-queryset-field-lookups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!