【问题标题】:Get objects from a many to many field从多对多字段中获取对象
【发布时间】:2012-10-31 17:26:30
【问题描述】:

我在模型中有一个名为“admins”的 m2m 字段,我需要从视图中获取该字段中所有选定的条目,即用户 ID。然后使用用户 ID 获取每个用户的电子邮件。有可能吗?

我想要做的确切的事情是向该平台内空间的所有管理员发送大量电子邮件。

空间模型:

class Space(models.Model):

    """     
    Spaces model. This model stores a "space" or "place" also known as a
    participative process in reality. Every place has a minimum set of
    settings for customization.

    There are three main permission roles in every space: administrator
    (admins), moderators (mods) and regular users (users).
    """
    name = models.CharField(_('Name'), max_length=250, unique=True,
        help_text=_('Max: 250 characters'))
    url = models.CharField(_('URL'), max_length=100, unique=True,
        validators=[RegexValidator(regex='^[a-z0-9_]+$',
        message='Invalid characters in the space URL.')],
        help_text=_('Valid characters are lowercase, digits and \
    admins = models.ManyToManyField(User, related_name="space_admins", verbose_name=_('Administrators'), help_text=_('Please select the \
        users that will be administrators of this space'), blank=True,
        null=True)
    mods = models.ManyToManyField(User, related_name="space_mods",
        verbose_name=_('Moderators'), help_text=_('Please select the users \
        that will be moderators of this space.'), blank=True, null=True)
    users = models.ManyToManyField(User, related_name="space_users", verbose_name=_('Users'), help_text=_('Please select the users that \
        can participate on this space'), blank=True, null=True)

查看只发送一封电子邮件:

@login_required
def add_intent(request, space_url):

    """
    Returns a page where the logged in user can click on a "I want to
    participate" button, which after sends an email to the administrator of
    the space with a link to approve the user to use the space.
    
    :attributes:  space, intent, token
    :rtype: Multiple entity objects.
    :context: space_url, heading
    """
    space = get_object_or_404(Space, url=space_url)
    #admins = space.admins??

    try:
        intent = Intent.objects.get(user=request.user, space=space)
        heading = _("Access has been already authorized")
        
    except Intent.DoesNotExist:
        token = hashlib.md5("%s%s%s" % (request.user, space,
                            datetime.datetime.now())).hexdigest()
        intent = Intent(user=request.user, space=space, token=token)
        intent.save()
        subject = _("New participation request")
        body = _("User {0} wants to participate in space {1}.\n \
                 Please click on the link below to approve.\n {2}"\
                 .format(request.user.username, space.name,
                 intent.get_approve_url()))
        heading = _("Your request is being processed.")
        send_mail(subject=subject, message=body,
                  from_email="noreply@ecidadania.org",
                  recipient_list=[space.author.email])

        # Send a notification to all the admins in that space
        #send_mass_mail()

    return render_to_response('space_intent.html', \
            {'space_name': space.name, 'heading': heading}, \
            context_instance=RequestContext(request))

【问题讨论】:

    标签: django django-models many-to-many


    【解决方案1】:

    你可以使用:

    space.related.all()
    

    返回用户的查询集

    【讨论】:

    • 它返回一个 AttributeError 空间对象没有“related_admins”imgur.com/nEMQi
    • 您不需要在此处使用相关名称。只需space.admins.all() 即可。
    • 当你想space.admins.all()返回RecursionError时会发生什么?
    【解决方案2】:

    对于 Django >= 1.9

    space.admins.all()
    

    作为mentioned by Salvatore Iovene

    【讨论】:

    • 获取 AttributeError: 'ManyToManyDescriptor' 对象没有属性 'all'
    【解决方案3】:

    获取所有 many_to_many 对象(不适用于特定空间),对我来说有效

    Space.admins.through.objects.all()
    

    (Django 2.14)

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 2019-09-18
      • 2018-02-28
      • 1970-01-01
      • 2022-01-22
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多