how to query a many to many relationship?

后端 未结 2 697
暗喜
暗喜 2021-01-16 12:59

I\'m trying to build an e-learning platform

I have users (Utilisateur) who can take several courses ,each course h

相关标签:
2条回答
  • 2021-01-16 13:07

    Ad 2. Yes, it's correct. But you have to keep in mind that when user starts some courses, and some of them have the same module(s) you could store only one mark for those modules. To prevent this you would need to create class like this:

    class UtilisateurCourseModule(models.Model):
        user   = models.ForeignKey(Utilisateur)
        course = models.ForeignKey(Course)
        module = models.ForeignKey(Module)
        score = models.IntegerField()
    

    Ad 1.

    for c in user.course.all(): # why course not courses?
        print "Course {}".format(c.titre)
        for m in c.module_set.all().order_by('modulecourse__order')
            print "Module {}".format(m.titre)
            try:
                print 'score: ', UtilisateurModule.objects.get(user=user,module=m).score
            catch UtilisateurModule.DoesNotExits:
                print 'score: ---'
    
    0 讨论(0)
  • 2021-01-16 13:25

    SOLVED

    1- This is how I've managed to do it :

        course = Utilisateur.objects.get(user=current_user).course.all() 
    
        course_sets = []
        for p in course:
            modules = Module.objects.filter(course__id=p.pk).order_by('modulecourse__order') 
            modules_sets = []
            for m in modules:                
                score = UtilisateurModule.objects.get(module=m,utilisateur=current_user)
                modules_sets.append((m, score))
            course_sets.append((p, modules_sets)) 
    

    2- I added course = models.ManyToManyField('Course') to Utilisateur

    and then added some manual verification that whenever A course is affected to a user the modules in that course are also affected to the same user in UtilisateurModule

    0 讨论(0)
提交回复
热议问题