- 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
- FileField having auto upload_to path by junaidmgithub 1 month ago
- LazyPrimaryKeyRelatedField by LLyaudet 1 month, 1 week ago
- CacheInDictManager by LLyaudet 1 month, 1 week ago
- MYSQL Full Text Expression by Bidaya0 1 month, 1 week ago
- Custom model manager chaining (Python 3 re-write) by Spotted1270 1 month, 2 weeks ago
Comments
Please login first before commenting.