使用Querysets在Django中的ForLoops中进行错误的迭代

时间:2016-03-22 01:40:20

标签: python django for-loop django-queryset

views.py;

    cvs = Cv.objects.all()
    cv = Cv.objects.filter(author = request.user)
    per = Person.objects.all()
    gr = Group.objects.filter(members__name=request.user)
    perr = Person.objects.filter(name=request.user)
    mem = Membership.objects.filter(group = gr, person = perr)


    form = GroupForm()


    context = {
        'gr': gr,
        'per':per,
        'mem':mem,
        'form': form,
        'cvs':cvs,
        'cv':cv,

    }

    return render(request, 'groups.html', context)

models.py:

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name


class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')
    description = models.TextField(max_length=350)

    def __str__(self):              # __unicode__ on Python 2
        return self.name


class Membership(models.Model):
    person = models.ForeignKey(Person)
    leader = models.BooleanField(default=False)
    group = models.ForeignKey(Group)
    role = models.CharField(max_length=50)

template.html:

{% for z in mem %}
   <div class="jumbotron">
     <div class="jumbo2">
        <form method="POST" class="post-form"> {% csrf_token %}
            <p id="name"><b>Groups name:</b> {{z.group}}</p><br>

                {% for member in z.group.members.all %}

                      <p><b>Member:</b> {{member.name}} 

                        {% if z.person.name == member.name %}

                      - {{z.role}}</p>

                        {% endif %}                                         

                {% endfor %}

            </form>

         </div>
       </div> 

  {% endfor %}

当我创建群组时,我的角色是#34;团队负责人&#34;,当我向群组添加某人时,他的角色是#No; Noob&#34;。我想显示该组的所有成员及其角色。问题是:我的实际输出是:

damian - Team leader
test                   <- and no role, but should be "Noob"

我想得到什么:

damian - Team Leader
test - Noob

任何人如何解决这个问题? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

由于隐含的变量名称(例如z),您的代码有点难以理解。

问题似乎是您只在z.person.name == member.name

打印角色

如果从循环中删除该条件,则它将显示组中的所有角色而不是一个。但要做到这一点,您需要通过member对象而不是z对象

来查找角色