Say I have a model with a Things table and a table of relationships between the things called ThingRelations. It should not be possible to delete a Thing when there are ThingRelations that point to it. This is how I'm trying to implement that:
from django.db import models
class ThingRelation(models.Model):
first_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)
second_thing = models.ForeignKey('Thing', on_delete=models.PROTECT)
class Thing(models.Model):
name = CharField(max_length=260)
How do I automatically delete a Thing when there are no more ThingRelations pointing to it?
CodePudding user response:
You have such options:
- A routine. It can be made as a
Commandand something likecrontab. Or it could be designed as aperiodiqroutine. This way you can repeatedly select allThingmodels which have no relations withThingRelation. signals.pyaction. This way when entry ofThingRelationis deleted, you should check both thefirst_thingandsecond_thingin order to know whether the have any moreThingRelationrelations pointing to them.- DB trigger (e.g. for PostgreSQL). The same idea as
signal.pysolution, but on DB level.
Which one should you choose? Depends on details of your exact objective. As for me, I use periodiq option on simple cases and DB trigger if I aim on high performance.
