Login

Finding related objects for instances in a queryset

Author:
akaihola
Posted:
March 8, 2011
Language:
Python
Version:
Not specified
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

  1. codigo alto nivel by MrRocklion 1 month ago
  2. Load template from specific app by Krzysiek555 1 month, 3 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 1 month, 3 weeks ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 months ago

Comments

Please login first before commenting.