Reputation: 6835
I'm not too sure how to find this through google and searching hasn't been leading me anywhere.
How do you relate 2 models in such a way that if you delete one entry in the admin panel, the other will automatically be deleted?
Thank You for any help.
EDIT: Updated with example. I want an Event to be able to describe the other competitors, and the Picture with the OneToOne relationship with the Event should be the primary contestant. So once the primary contestant gets deleted, I also want to delete the Event. Unfortunately, I can't just add a ForeignKey relationship in Event or that would cause an error. So, is there someway to do this for a OneToOne relationship?
class Event(models.Model):
competitors = models.ManyToManyField('Picture',null=True,blank=True)
class Picture(models.Model):
competition = models.OneToOneField(Event)
Upvotes: 0
Views: 161
Reputation: 39659
Suppose you have two models:
class ModelA(models.Model):
name = models.CharField(max_length=30)
class ModelB(models.Model):
abc = models.CharField(max_length=30)
model_a = models.ForeignKey(ModelA)
Now lets do some working example:
modelAObj = ModelA.objects.create(name='aamir')
modelBObj = ModelB.objects.create(abc='cde', model_a=modelAObj)
modelAObj.delete() # this will also delete the modelBObj
Upvotes: 1
Reputation: 51665
Quoting django docs:
When Django deletes an object, by default it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.
Then, this is the default behavior.
See on_delete options for further details:
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
The possible values for on_delete are found in django.db.models:
CASCADE: Cascade deletes; the default.
...
Upvotes: 4