Login

Finding related objects for instances in a queryset

Author:
akaihola
Posted:
March 8, 2011
Language:
Python
Version:
Not specified
Tags:
db orm related
Score:
1 (after 1 ratings)

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>]}
1
2
3
4
5
6
7
8
9
from django.db.models.deletion import Collector
from django.db import router
from myapp.models import MyModel

def get_related(queryset):
    using = router.db_for_read(queryset.model)
    coll = Collector(using=using)
    coll.collect(queryset)
    return coll.data

More like this

Comments

Please login first before commenting.