Reputation: 1154
Here is my code :
communeList = [
"78",
"95",
"77",
"91",
"92",
"93",
"94",
"75",
]
commune_list_1 = list(Commune.objects.all())
commune_list = []
for c in commune_list_1 :
if c.codePostal[0:2] not in communeList :
commune_list.append([c])
CodePostal is a charfield with 6 characters and i would like a query to return me all the codepostal which begins (the first 2 characters) by the element of the list communeList.
Regards
Upvotes: 0
Views: 68
Reputation: 77902
Your model is not properly designed for this query - you'd need to split the zipcode into it's two parts (the department code - 2 to 3 chars, depending on whether it's in the DOMS-TOMS - and the "bureau distributeur" id for the remaining characters). Then you can query on department code:
commune_list = Commune.objects.filter(department_code__in=communeList)
Or you can OR together "startswith" queries, cf Rakesh's answer, but this is not going to be very efficient, specially if you have all 36000 french communes in your db. That's ok for a one-shot script, but if filtering on a list of departments is an often used feature of your app, you certainly want to change your schema.
Note that for historical reasons, the department_code does not necessarily match the actual city's department, and are not cities identifiers either (you want the insee codes for this).
Also - totally unrelated but -, your naming is inconsistant (mixedCase + all_lower), misleading (your three variables are basically named "commune list" - makes it really hard to remember which is which), and eventually plain wrong (the first list is a list of department codes, not a list of communes). Hint: a good naming convention for collections is the plural form ("une commune" => "des communes").
Upvotes: 1
Reputation: 82765
You can use __startswith
Ex:
from django.db.models import Q
communeList = [
"78",
"95",
"77",
"91",
"92",
"93",
"94",
"75",
]
que = Q()
for i in communeList:
que |= Q(codePostal__startswith=i)
Commune.objects.filter(que)
Upvotes: 2