5

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

6
  • I've modified your question to make it slightly clearer what the issue is. feel free to roll back if this is incorrect Commented Dec 9, 2016 at 12:03
  • hi i don tneed it to be case insentive? the question was how i can use contains and in, in the same query. Commented Dec 9, 2016 at 12:14
  • icontains is a case insensitive contains, contains on its own is what in essentially does anyway Commented Dec 9, 2016 at 12:15
  • ive edtited to try make the question more clear Commented Dec 9, 2016 at 12:17
  • 1
    "contains on its own is what in essentially does anyway" - err, quite not actually. field__contains='xxx' translates to a field like "%xxx%" (mysql syntax) clause, while field__in=("a", "b", "c") translates to a standard SQL in clause, ie field in("a", "b", "c") - which is logically equivalent to (field = 'a' or field = 'b' or field='c'). Commented Dec 9, 2016 at 12:38

2 Answers 2

16

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use Django's Overlap filter to achieve this.

From the docs:

Returns objects where the data shares any results with the values passed. Uses the SQL operator &&.

So, you could try:

site = SiteData.objects.filter(address__overlap=postcodes))

2 Comments

It should be noted that this only works for PostgreSQL.
It should also be noted this only works with Array type fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.