When deleting objects in Django's admin interface, it lists other objects which would be deleted and asks for confirmation. This snippet does the same programmatically.
The snippet works in Django 1.3 (more specifically, revision 14507 or later). It uses Django internals which are not a part of the public API, so this might not work with future versions.
Usage:
`polls/models.py`:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
def __unicode__(self):
return '%s %s' % (self.poll, self.choice)
`$ ./manage.py shell`
>>> from polls.models import Poll, Choice
>>> from datetime import datetime
>>> from pprint import pprint
>>> poll1 = Poll.objects.create(question='Me?')
>>> Choice.objects.create(poll=poll1, choice='Yes')
>>> Choice.objects.create(poll=poll1, choice='No')
>>> poll2 = Poll.objects.create(question='Really?')
>>> Choice.objects.create(poll=poll2, choice='Yes')
>>> Choice.objects.create(poll=poll2, choice='No')
>>> pprint(get_related(Poll.objects.all()))
{<class 'polls.models.Poll'>: [<Poll: Me?>, <Poll: Really?>],
<class 'polls.models.Choice'>: [<Choice: Me? Yes>,
<Choice: Me? No>,
<Choice: Really? Yes>,
<Choice: Really? No>]}