如果字段名存在于字符串中,如何使用Django模型过滤器从数据库查询对象

问题描述 投票:0回答:1

如何通过使用objects.filter()来检查字符串中是否存在django查询对象。就像,如果我想使用名为“ Foo”的字段名(如果它在字符串“ Foo Bar”中)进行过滤。我尝试了以下行,但当然不起作用:

# name = Foo
obj.objects.filter(name__in='Foo Bar') # Empty Query list
django django-models django-filter
1个回答
1
投票

您可以找到所有子字符串并使用in

from itertools import combinations

my_str = 'Foo Bar'
substrings = [my_str[x:y] for x, y in combinations(range(len(my_str) + 1), r = 2)]
obj.objects.filter(name__in=substrings)
© www.soinside.com 2019 - 2024. All rights reserved.