开发者

How to Query/Filter M2M 'through' object in Django

I have the following basic model…

  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)

I'd like to have a queryset that queries all Person objects that are not within a given Campaign.

It'd be 开发者_开发技巧nice if it was as easy as:

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

but we know that doesn't work.

To be more specific, I'm trying to get this to work in a form class as follows and the Q object comment seems right but I can't get it to work… Here's my form:

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()


I believe this will do it.

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


Here's the answer… the problem was that my form was for the Recipient object instead of the Campaign object… the Furbeenator answer was a good step in the right direction… along with some help on the 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',]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜