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.朋友:
@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 %}
Create a new group here:
{% csrf_token %} {{ form.as_p }}
{% for m in mem %}
Name of group: {{ m.group }}
Member: {{ m.person }}
{% endfor %} {% endblock %}
问题是我想要使用的时候
Membership.objects.filter(person=request.user)
并得到错误:
ValueError at /groups/ Cannot query "damian": Must be "Person" instance.