如何“通过”查询/过滤 M2M Django 中的对象

发布于 2024-12-07 01:56:32 字数 1796 浏览 0 评论 0原文

我有以下基本模型...

  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)

我想要一个查询集来查询不在给定营销活动中的所有 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()

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

热情消退 2024-12-14 01:56:32

我相信这会做到的。

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

I believe this will do it.

from django.db.models import Q
Person.objects.filter(~Q(id__in=<mycampaign>.recipients.all())
暗恋未遂 2024-12-14 01:56:32

这是答案...问题是我的表单是针对 Recipient 对象而不是 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',]

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',]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文