Home > Net >  Django IN Query with different values of combination of two columns
Django IN Query with different values of combination of two columns

Time:07-28

I have to filter user from different city and state combination like Users from cities [[Mumbai,MH],[Ahmedabad,GJ],...]

Where city = Mumbai and state = MH

This is what i am doing now

 users = cls.objects.annotate(unique_city=ExpressionWrapper(Concat(F('city'),F('state'),output_field=CharField()), output_field=CharField())).filter(unique_city__in = city_list)

where city_list = [MumbaiMH,AhemadabadGj,...] Is there is a better way to do this

I have user model with field state and city

And city model with field state and city(unique together)

CodePudding user response:

You might use Q objects instead.

Given a list of tuples searchlist = [(city1, state1), (city2, state2), ...]

if len( searchlist) == 0:
    query = cls.objects.none()

else:
    city, xstate = searchlist[0]
    q = Q( city=city, state=xstate)

    for city, xstate in searchlist[1:] :
         q = q | Q( city=city, state=xstate)

    query = cls.objects.filter( q)

Note: using xstate not state because SO auto-colorizing is doing really wierd things if I use state. It thinks its a reserved word, although in Python it's not?

  • Related