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

  1. Signal to post new saved objects to Twitter by arthurfurlan 6 years, 2 months ago
  2. Modifying the fields of a third/existing model class by marinho 4 years, 4 months ago
  3. ParentModel and ChildManager for Model Inheritance by jpwatts 6 years, 7 months ago
  4. Bitwise operator queryset filter by hgeerts@osso.nl 4 years, 11 months ago
  5. SerializedObjectField by dominno 5 years, 1 month ago

Comments

Please login first before commenting.