Задать вопрос

Тел: +7 965 3737 888

415

Просмотров

0

Ответов

Finding related objects for instances in a queryset

<p>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.</p>
<p>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.</p>
<p>Usage:</p>
<p>polls/models.py:</p>
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)

<p>$ ./manage.py shell</p>
&gt;&gt;&gt; from polls.models import Poll, Choice
&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; from pprint import pprint
&gt;&gt;&gt; poll1 = Poll.objects.create(question='Me?')
&gt;&gt;&gt; Choice.objects.create(poll=poll1, choice='Yes')
&gt;&gt;&gt; Choice.objects.create(poll=poll1, choice='No')
&gt;&gt;&gt; poll2 = Poll.objects.create(question='Really?')
&gt;&gt;&gt; Choice.objects.create(poll=poll2, choice='Yes')
&gt;&gt;&gt; Choice.objects.create(poll=poll2, choice='No')
&gt;&gt;&gt; pprint(get_related(Poll.objects.all()))
{&lt;class 'polls.models.Poll'&gt;: [&lt;Poll: Me?&gt;, &lt;Poll: Really?&gt;],
 &lt;class 'polls.models.Choice'&gt;: [&lt;Choice: Me? Yes&gt;,
                                 &lt;Choice: Me? No&gt;,
                                 &lt;Choice: Really? Yes&gt;,
                                 &lt;Choice: Really? No&gt;]}

Вопрос полезен? Да0/Нет0
file_4932.py(276.0б)
None