3👍
You should use signals.
@receiver(post_delete, sender=B)
def delete_a(sender, instance, **kwargs):
# instance.type_b is the object which you want to delete
2👍
A best way to do it, just add [on_delete=models.CASCADE][1]
:
class A(models.Model):
name = models.CharField(max_length=128)
class B(modes.Model):
type_b = models.ForeignKey(A,on_delete=models.CASCADE)
- [Django]-Django 1.11 authentication set_unusable_password vs setting password to None
- [Django]-Adding days to a date via the ORM
- [Django]-Getting data from an Excel sheet
- [Django]-How can I include user profile's images/logos on django comments
- [Django]-Django test client vs. django-pytest
0👍
You can use post_delete signal to delete the parent as suggested by Davit Tovmasyan.
BUT because of the cascading nature as the parent A object is deleted, it will also delete all the connected B objects which will inturn emit post_delete
signal on B model. So on the second emit of post_delete
the signal handler tries to delete an already deleted item which causes 'NoneType' object has no attribute 'delete'
. You can use exception handler or just use the if condition to handle this.
def delete_parent(sender, instance, **kwargs):
if instance.type_b:
instance.type_b.delete()
post_delete.connect(delete_parent, sender=B)
- [Django]-In Django, how to rename user model?
- [Django]-Django admin filters on remote field via get_list_filter
- [Django]-Django – How to redirect differently using LoginRequired and PermissionRequired?
- [Django]-How do I use a datepicker on a simple Django form?
- [Django]-Testing for a ValidationError in Django
Source:stackexchange.com