访问Django中间模型组中的字段

时间:2016-03-09 02:12:16

标签: python django model many-to-many

我正在创建一个包含Person和Membership的Group模型,所有这些都在Django docs中描述。

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

    def __str__(self):              
        return self.name


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

    def __str__(self):              
        return self.name


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

我只是将这一切都放在视图中,因为我想在我的网络应用程序中将这个“创建组”作为一个功能。

views.py:

@login_required
def groups(request):
user = request.user

if request.method == "POST":
    form = GroupForm(request.POST)
    if form.is_valid():
        formm = form.save(commit=False)

        g = Group.objects.create(name = formm.name)
        p = Person.objects.create(name=request.user)
        m = Membership.objects.create(person=p, group=g, leader=True)



        gr = Group.objects.all()
        per = Person.objects.all()
        mem = Membership.objects.all()
        context = {
        'gr': gr,
        'per':per,
        'mem':mem,
        'form': form,
        }
        return render(request, 'groups.html', context )

else:

    gr = Group.objects.all()
    per = Person.objects.all()
    mem = Membership.objects.all()
    form = GroupForm()

    context = {
        'gr': gr,
        'per':per,
        'mem':mem,
        'form': form,
    }

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

groups.html:

{% block profile %}
  <div class="jumbotron">
    <h4>Create a new group here:</h4>
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Go!</button>
    </form>
  </div>


        {% for m in mem %}
        <div class="jumbotron">
          <br>
            <p><b>Name of group:</b> {{ m.group }} </p> 
            <p><b>Member:</b> {{ m.person }} </p>
          <br>
        </div>
        {% endfor %}



{% endblock %}

问题在于我想使用

Membership.objects.filter(person=request.user) 

并收到错误:

ValueError at /groups/
Cannot query "damian": Must be "Person" instance.

其中damian是request.user

的名称

我只想过滤此内容,仅在模板中显示所选的会员资格,群组等......

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这样做,

Membership.objects.filter(person__name=request.user)

p = Person.objects.get(name=request.user)
Membership.objects.filter(person=p)

您必须在Person过滤器查询中将person类实例传递给Membership参数。