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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With