简体   繁体   中英

Django models queryset with array

I want to make a function which will return applications which names contains some text.

Let's assume that we have below models:

class Application(models.Model):
    name = models.CharField(max_lenght=100)

Example values: "T2 AAA", "T2 BBB", "FSA KK" etc.

Now I want to write function which should return me application T2 AAA if attribute of this function will be AAA:

def getApplication(request, title):
    titleVars = title.split(' ')
    applications = Application.objects.filter(name__in=titleVars)

Honestly I don't know how to do that, I think that I should use icontains however I don't know how it applies to the array titleVars .

Example execution:

getApplication(request, 'Some text whatever T2 AAA XXX/K')

Thanks in advance

I think you are looking for like search.

Using Q() -

from django.db.models import Q

obj_list = Application.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in titleVars]))

And thats the recommended way.

Other options -

You can do this with django-like (ref - answer ):

Application.objects.filter(name__like=titleVars[1])

Other way is you can loop thru your array item, and do regex check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM