我的数据库中有社团的数据,但也有一些社团包含城市名称和地名。我想检查社团名称是否包含城市名称和地方名称,并删除它们或更新社会名称。
models\locality.py
class Society(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase.
updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase.
locality = models.ForeignKey('Locality', models.DO_NOTHING, db_column='localityId', blank=True, null=True, related_name='society_set') # Field name made lowercase.
dot_com_database_id = models.IntegerField(db_column='dotComDatabaseId', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'societies'models\society.py
class Locality(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase.
updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase.
city = models.ForeignKey('City', models.DO_NOTHING, db_column='cityId', blank=True, null=True, related_name='locality_set') # Field name made lowercase.
connect_database_id = models.IntegerField(db_column='connectDatabaseId', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'localities'它会消除你的疑虑:反复遍历那些确实有名字的社会和每个社会。对于社会而言,是否存在城市和地方的附加问题。从社会名称中删除城市名称和地方名称,并更新社会名称。
例如:
数据库中的社团名称:Lodha Downtown Dombivli East Thane
在上面的例子中,社会名称是'Loadha市中心‘,但它也包含了地方名称'Dombivli East’和城市名称'Thane‘。
如何通过循环或任何迭代检查社团名称是否包含城市或地区名称?
发布于 2022-03-03 10:14:18
检查任何社团名称是否包含使用列表()的本地名称的子字符串。
为了检查它是否包含,我们将使用象征并使用python的reduce函数遍历每个locality_names_list。
from functools import reduce
import operator
from django.db.models import Q
locality_names_list = list(Locality.objects. values_list('name', flat=True)
society_names_contain_locality = Society.objects.filter(reduce(operator.and_, (Q(name__icontains=name) for name in locality_names_list)))
print(society_names_contain_locality) society_names_contain_locality返回您想要的社会列表,您可以迭代它来更新或删除。
要更新,可以使用update()或save():
for society in society_names_contain_locality:
society.update(name="???") #or society.delete() if delete或者,如果您想同时处理所有这些值,只需使用一个值:
society_names_contain_locality.update(name="???")
society_names_contain_locality.delete() #warn: this delete all of themhttps://stackoverflow.com/questions/71333550
复制相似问题