如何在Django中查询/过滤M2M'到'对象

时间:2011-09-28 06:08:52

标签: python django django-forms

我有以下基本型号......

  class Campaign(models.Model):
    name = models.CharField(_('name'), max_length=80, unique=True)
    recipients = models.ManyToManyField('Person', blank=True, null=True, through='Recipient')


  class Recipient(models.Model):
    campaign = models.ForeignKey(Campaign)
    person = models.ForeignKey('Person')


  class Person(models.Model):
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

我想要一个查询集查询不在给定Campaign中的所有Person对象。

如果它像以下一样简单:

Person.objects.all().exclude(<mycampaign>.recipients.all())

但我们知道这不起作用。

更具体一点,我试图让它在一个表单类中工作如下,Q对象注释似乎正确,但我不能让它工作......这是我的表单:

class RecipientsForm(forms.Form):
  def __init__(self, campaign, *args, **kwargs): 
    self.campaign = campaign
    self.helper = FormHelper()
    self.helper.add_input(Submit('submit','Add',css_class='primaryAction'))
    self.helper.layout = Layout(
        Fieldset(
          '',
          'recipients',
          css_class='inlineLabels')
      )
    return super(RecipientsForm, self).__init__(*args, **kwargs)

  recipients = forms.ModelMultipleChoiceField(
  # old queryset queryset=Person.objects.all(),
                 queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
                 widget=forms.widgets.CheckboxSelectMultiple,
                 label="Add Recipients",
                 required=True,)

  def save(self, force_insert=False, force_update=False, commit=True):
    recipients = self.cleaned_data['recipients']
    for person in recipients:
      recipient = Recipient(campaign=self.campaign,person=person)
      recipient.save()

2 个答案:

答案 0 :(得分:1)

我相信这样做会。

from django.db.models import Q
Person.objects.filter(~Q(id__in=<mycampaign>.recipients.all())

答案 1 :(得分:1)

这是答案......问题是我的表单是针对收件人对象而不是Campaign对象... Furbeenator答案是正确方向的一个很好的步骤...以及对django IRC的一些帮助

class RecipientsForm(forms.ModelForm):

  def __init__(self, *args, **kwargs):
    self.campaign = kwargs.pop('campaign', None)
    super(RecipientsForm, self).__init__(*args, **kwargs)

    if self.instance and self.campaign:
      self.fields['recipients'] = forms.ModelMultipleChoiceField(
        queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
        widget=forms.widgets.CheckboxSelectMultiple,
        label='Recipients', help_text='Pick the recipients to add to the campaign',
        required=False,
      )
    elif self.campaign:
      self.fields['recipients'] = forms.ModelMultipleChoiceField(
        queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
        widget=forms.widgets.CheckboxSelectMultiple,
        label='Recipients', help_text='Pick the recipients to add to the campaign',
        required=False,
      )
    else:
      pass

  def save(self, force_insert=False, force_update=False, commit=True):
    recipients = self.cleaned_data['recipients']
    for person in recipients:
      recipient = Recipient(campaign=self.campaign,person=person)
      recipient.save()

  class Meta:
    model = Campaign
    fields = ['recipients',]