Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to elegantly "swap" rows in all foreign key and many to many fields in django?

Tags:

django

I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so:

class Store(Model):
 store_name = TextField()
 entities = ManyToManyField(Entity)

class Purchase(Model):
 datetime = DatetimeField(auto=True)
 entity = ForeignKeyField(Entity)

In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out

so....

for p in Purchase.objects.filter(entity=cocacola_entity):
 p.entity = coca_cola_entity
 p.save()
for s in Purchase.objects.filter(entities=cocacola_entity):
 s.entities.remove(cocacola_entity)
 s.entities.add(coca_cola_entity)
 s.save()
cocacola_entity.delete()

Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one)

like image 785
Stupid.Fat.Cat Avatar asked Dec 04 '25 19:12

Stupid.Fat.Cat


1 Answers

You can use update() to update the foreign key:

Purchase.objects.filter(entity=cocacola_entity).update(entity=coca_cola_entity)

You can also pass multiple items to add(), and then clear the other relation in case of a many-to-many field:

coca_cola_entity.store_set.add(*cocacola_entity.store_set.all())
cocacola_entity.store_set.clear()
like image 56
knbk Avatar answered Dec 07 '25 14:12

knbk