V
V
Vitaly Khvan2018-06-05 13:06:53
Django
Vitaly Khvan, 2018-06-05 13:06:53

How to properly do group_by in django2?

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)

Now, when passing the test, this is the result:
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
Actually, how can you group these data to display in template ?
In SQL cases, I would write a query
SELECT * FROM `questionnaire_testingstep` GROUP BY `question_id`

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question