Проверка наличия элемента в поле ManyToMany в 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 stud not in session.attendees.all():
            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.

Вернуться на верх