'how can remove city name and update society name and save it into the database?
So I want to know how can I remove the city name from the society name and update the society name and save it into the database?
Below code is taking all the society names that contain the city name. but I want to update all the society's names and save them.
qs = Society.objects.all()
citys = City.objects.values_list('name', flat=True)
clauses = (Q(name__iendswith=name) for name in citys)
query = reduce(operator.or_, clauses)
data = qs.filter(query)
Thanks!!
Solution 1:[1]
1)I advice you to use my first comment in your question it is better to have a foreignkey for the city
2)Here is how you can achieve it without the foreignkey.
qs = Society.objects.all()
citys = City.objects.values_list('name', flat=True)
clauses = (Q(name__iendswith=name) for name in citys)
query = reduce(operator.or_, clauses)
datas = qs.filter(query)
for data in datas:
name = data.name
new_name = " ".join(name.split()[:-1])
data.name = new_name
data.save()
this will do the trick but this is actually not a very good approach here is why:
let us say you have a company name google paris then new_name will be google,but let us
assume you have google new york city then new_name will be google new york
this is not actually what you want.
to make this work i advice you to add # before adding the city name something like
google # paris then the answer will be
qs = Society.objects.all()
citys = City.objects.values_list('name', flat=True)
clauses = (Q(name__iendswith=name) for name in citys)
query = reduce(operator.or_, clauses)
datas = qs.filter(query)
for data in datas:
name = data.name
new_name = name.split('#')[0]
data.name = new_name
data.save()
This is just an idea how you can achieve it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thierno Amadou Sow |
