era5tone
era5tone

Reputation: 657

Check if a User type exists in ManyToManyField in Django?

I have a Course Model which contains a user who creates the course and contains a enrolled ManyToManyField which lets users enroll in the course.

class Course(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_owner')
    enrolled = models.ManyToManyField(User)
    ...

The user model contains two types - Teacher (Created the course) and Student (enrolls)

class User(AbstractUser):
    is_student = models.BooleanField(default=True)
    is_teacher = models.BooleanField(default=False)

I want a MyCourses View where the teacher can view his created_courses and the student can view his enrolled courses.

def MyCourses(request):
    user = request.user
    courses = Course.objects.filter(user=user)

    context = {
        'courses': courses
    }

    return render(request, 'classroom/mycourses.html', context)

This works for the teacher part but how I can check if a student is enrolled in the course?

Thanks.

Upvotes: 1

Views: 350

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You can add an extra condition and use a logical or:

from django.db.models import Q

def MyCourses(request):
    user = request.user
    courses = Course.objects.filter(Q(user=user) | Q(enrolled=user))

    context = {
        'courses': courses
    }

    return render(request, 'classroom/mycourses.html', context)

to prevent loading the same Course multiple times, you can use .distinct() [Django-doc]:

from django.db.models import Q

def MyCourses(request):
    user = request.user
    courses = Course.objects.filter(Q(user=user) | Q(enrolled=user)).distinct()

    context = {
        'courses': courses
    }

    return render(request, 'classroom/mycourses.html', context)

Upvotes: 3

Related Questions