Search code examples
djangolistmodels

Django - Passing iteratable data from 2 related models to template


I have 2 models which look like this,

class OnlineTest(models.Model):
    name = models.CharField(max_length=50)
    questions = models.ManyToManyField(Question)

class OnlineTestProgress(models.Model):
    examinee = models.ForeignKey(MSchoolMateUser)
    quiz = models.ForeignKey(OnlineTest)
    complete = models.BooleanField(default=False, blank=False)

Inside of my template I want to show the user all the tests and their status. So, if the test status in the OnlineTestProgress model is COMPLETE, it will be a green row and if it is NOT TAKEN it will be a red row.

This requires me to iterate over 2 models and I am not able to do this.

For m tests and n users, the OnlineTestProgress model will have m.n entries while the OnlineTest model will have m entries.

I considered writing a function in the OnlineTest model but not sure if it the right approach.

Thank You for your time. Your help is much appreciated.


Solution

  • Why do you need to iterate over two models? It seems like you just need to iterate over OnlineTestProgress?

    If OnlineTestProgress only has taken tests, then just add all of the tests that aren't in OnlineTestProgress on the back end

    or just iterate over OnlineTest and check if each one is in OnlineTestProgress by passing all OnlineTest in OnlineTestProgress as a list called taken_list and do

    {% for test in OnlineTest %}
    
        {% if test in taken_list %} [make the row green] {% endif %}
    
    {% endfor %}