models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Specialty(models.Model):
# specialty name
name = models.CharField(max_length=255)
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class Subject(models.Model):
# specialty key
specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, null=True)
# subject name
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Question(models.Model):
# subject key
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
# question body
body = models.CharField(max_length=255)
# timestamp create
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.body
class Answer(models.Model):
# question key
question = models.ForeignKey(Question, on_delete=models.CASCADE)
# answer body
body = models.CharField(max_length=255)
# if answer correct state true
is_correct = models.BooleanField()
# suffix to answer
suffix = models.CharField(max_length=1)
# timestamp create
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.body
class Testing(models.Model):
# Пользователь который начал тестирование
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
# Предмет
subject = models.ForeignKey(Subject, on_delete=models.DO_NOTHING, null=True)
# Дата начала тестирования
created_at = models.DateTimeField(default=timezone.now)
# Дата окончания тестирования
done_at = models.DateTimeField(null=True)
class TestingStep(models.Model):
# Key тестирования
testing = models.ForeignKey(Testing, on_delete=models.CASCADE)
# Key вопроса
question = models.ForeignKey(Question, on_delete=models.DO_NOTHING)
# Key ответа
answer = models.ForeignKey(Answer, on_delete=models.DO_NOTHING)
# Дата ответа
created_at = models.DateTimeField(default=timezone.now)
Теперь при прохождении тестирования получается вот такой результат:
created_at: now() answer_id: 1, question_id: 1
created_at: now() answer_id: 2, question_id: 1
created_at: now() answer_id: 3, question_id: 1
Собственно как можно сгруппировать эти данные для вывода в template ?
В случаи SQL я бы написал запрос
SELECT * FROM `questionnaire_testingstep` GROUP BY `question_id`