Search code examples
pythonhtmldjangomanytomanyfield

Checking whether element is in ManyToMany field in Django


Hi so I have an attend session button that when clicked adds the user to the session. I got it working but I want to add a check to see whether the user is already in the ManyToMany field of attendees before I add them. How would I go about doing that?

Here is my view for it

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'))

Solution

  • You can check with:

    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.