检查元素是否在 Django 的 ManyToMany 字段中

Checking whether element is in ManyToMany field in Django

您好,我有一个参加会话按钮,单击该按钮会将用户添加到会话中。我让它工作但我想添加一个检查以查看用户是否已经在我添加之前的与会者的 ManyToMany 字段中。我该怎么做?

这是我的看法

def attend_session(request):

    session = Study.objects.get(pk=request.POST['session_id'])
    stud = Student.objects.get(student_user=request.user)

    if request.method == "POST":
        # Add check here to see if student is already attending
        session.attendees.add(stud)
        session.save()

    return HttpResponseRedirect(reverse('study:sessions'))

您可以查看:

from django.shortcuts import get_object_or_404, redirect

def attend_session(request):
    session = get_object_or_404(Study, pk=request.POST['session_id'])
    stud = get_object_or_404(Student, student_user=request.user)

    if request.method == 'POST':
        if <strong>stud not in session.attendees.all()</strong>:
            session.attendees.add(stud)

    return redirect('study:sessions')

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.


Note: You can make use of redirect(…) [Django-doc] instead of first calling reverse(…) [Django] and then wrap it in a HttpResponseRedirect object [Django-doc]. The redirect(…) function does not only offer a more convenient signature to do this, it also for example will use the .get_absolute_url() method [Django-doc] if you pass it a model object.