Make a count in relationship Many to Many

1

I'm trying to put in a view the number of students enrolled in a course using the following Models below.

I can not change the columns of the Models, since the database already exists and I'm just making another system from it.

But how does it work? So:

  

1 course (MdlCourse) has N enrollment types (MdlEnrol).

     

N enrollment types have N enrollments. (MdlUserEnrolments)

class MdlCourse(models.Model):
    id = models.BigAutoField(primary_key=True)
    fullname = models.CharField(max_length=200)

class MdlUserEnrolments(models.Model):
    id = models.BigAutoField(primary_key=True)
    status = models.BigIntegerField()
    enrolid = models.ForeignKey(MdlEnrol, on_delete = False, db_column = 'enrolid')

class MdlEnrol(models.Model):
    id = models.BigAutoField(primary_key=True)
    enrol = models.CharField(max_length=20)
    status = models.BigIntegerField()
    courseid = models.ForeignKey(MdlCourse, on_delete = False, db_column = 'courseid')

The Model MdlUserEnrolments does not have the Course ID. It has the subscription type ID. And the enrollment type table has the course ID.

That is, I need to walk two tables to have the number of students enrolled. This is using Django's relationship methods, since I did not want to make a RawSQL .

What I've achieved so far:

{{ course.mdlenrol_set.mdluserenrolments_set.count }}

This is bringing empty. When I just make the code below, it brings up the amount of enrollment types that the course has. So I think I'm getting close.

{{ course.mdlenrol_set.count }}
    
asked by anonymous 10.01.2018 / 12:02

2 answers

2

You can filter students this way:

MdlUserEnrolments.objects.filter(enrolid__courseid=course.id).count()

Let's say you want to put the filter value in each course of the context:

courses = MdlCouses.objects.all()
for course in courses:
    count = MdlUserEnrolments.objects.filter(enrolid__courseid=course.id).count()
    course.count = count

Now in your template it is possible to access the number of students of each course like this:

{{course.count}}
    
11.01.2018 / 13:05
1

From one search on select_related link

With it you can scroll through your tables in more optimized ways like:

user = MdlUserEnrolments.objects.select_related('enrolid')

To access the fields in the related table you can use the template:

{% for u in user %} Estatos do MdlUserEnrolments: {{ u.status }} Estatos do enrolid: {{ u.enrolid.status }} {% endfor %}

I just did it with 2 tables so far, but if I'm not mistaken you can do something like: u.enrolid.courseid.fullname to print

A get you could do type so user = MdlUserEnrolments.objects.select_related('enrolid').get(enrolid__status=10)

    
11.01.2018 / 18:27