The reason why your code doesn't work is because the query in the outer loop is executed once at the start, but each object can be updated in the inner loop, which causes them to be stale.
As an example, after you create all your objects, you have ["A", "BAB", "CBB"]. When mod1
is "A", it changes "BAB" to "BB", but the second object in your outer loop has already been loaded, so when the second iteration of the outer loop occurs it queries the database for name__contains="BAB"
instead of name__contains"BB"
, as you expect.
You can fix this by mutating all your objects in memory (assuming your table is small enough):
objects = list(mymodel.objects.all())
for mod1 in objects:
for mod2 in objects:
if mod1.name in mod2.name and mod1.id != mod2.id:
mod2.name = ''.join(mod2.name.split(mod1.name))
for mod1 in objects:
mod1.save()