Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Query using contains with a list as a source?

Tags:

python

django

I have a list of postcodes for example:-

postcodes = ['LDN 4DN','MAN 4RF']

The address field has the post code in it, sample address fields are

'1 downing street, London, England, LDN 4DN' '10 the avenues, Manchester, England, MAN 4RF' '20 the Highalnds, Scotland, SCT L40'

Im using

site = SiteData.objects.filter(address__icontains=postcodes[0]))

In a loop to get each site, but that seems a bit lengthy, is it possible to do contains in?

can i run a query to get for example the records for the two postcodes in the list?

Thanks

like image 745
AlexW Avatar asked Dec 09 '16 11:12

AlexW


1 Answers

That wont work, obviously - but you can use models.Q to build a "or" query:

import operator

clauses = (Q(address__icontains=p) for p in postcodes)
query = reduce(operator.or_, clauses)
site = SiteData.objects.filter(query)
like image 75
bruno desthuilliers Avatar answered Sep 23 '22 21:09

bruno desthuilliers