0

Considering those classes:

class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

class Baz(models.Model):
    bar = models.ForeignKey(Bar)

class XXX(models.Model):
    field = models.ForeignKey(field_related_to_FOO_somehow)
...

Given an instance foo=Foo.objects.get(...) that a user want to delete, i want to provide him a view of all the objects he's about to delete. Thus, how can i retrieve all the instances of Bar, Baz and all other related objects XXX that will be deleted in cascade if the user confirm?

Guillaume Thomas
  • 2,220
  • 2
  • 24
  • 33
  • Could you use the same function as the django admin uses? https://github.com/django/django/blob/1.9.7/django/contrib/admin/utils.py#L119 – Håken Lid Jun 15 '16 at 08:07
  • 1
    Here's a similar question : http://stackoverflow.com/questions/12158714/how-to-show-related-items-using-deleteview-in-django – user2021091 Jun 15 '16 at 08:11

2 Answers2

0
foo = Foo.objects.get(id=foo_id)

bar = Bar.objects.filter(foo=foo)

baz = Baz.objects.filter(bar=bar)

baz.delete()
bar.delete()

or just

foo.delete()
dmitryro
  • 3,463
  • 2
  • 20
  • 28
0

You can use on_delete=models.SET_NULL this will set None when delete related objects.

docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey

Rahul Vivek
  • 196
  • 1
  • 3