如何按用户对列表项进行分组

时间:2018-08-23 17:09:21

标签: django django-models django-queryset

我有一个带有外键Edp的对象。用户可以根据设计拥有多个RespostaEdp。但是,在打印列表时,我想按用户对它们进行分组。关于如何完成这项工作的任何想法?我尝试了以下解决方案,但无法访问用户值。

@teacher_required
def listarRespostasEDA(request):

    edpsTodas = Edp.objects.all()
    title = 'Estruturas Digitais Pedagogicas'
    template = 'edp/listarEDArespondida.html'
    edps = list()

    for edp in edpsTodas:

        if edp.respostas.all().count() != 0:
        # if not edp.respostas.none:
            edps.append(edp)


    return render(request, template, {'title': title, 'edps': edps})

def listaAlunosResponderamEdp(request, slug):
    edp = get_object_or_404(Edp, slug=slug)
    # respostas = RespostaEdp.objects.filter(edp=edp)
    lista = list()
    respostas = RespostaEdp.objects.filter(edp=edp).values('aprendiz').distinct().order_by('aprendiz')

    for r in respostas:
        for k,v in r.items():
            aluno = User.objects.filter(pk=v)
            lista.append(aluno)
            print (lista)


    return render(request, 'edp/teste.html', {'lista':lista})
class RespostaEdp(models.Model):

edp = models.ForeignKey(Edp, verbose_name='Edp', related_name='respostas', on_delete=models.CASCADE)
video_embedded = EmbedVideoField(blank=True, null=True)
texto = models.TextField('Texto', blank=True)
video = models.FileField(upload_to='video/', storage=upload_storage, default="media/none.mp4")
aprendiz = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='aluno', related_name='respostaAluno', on_delete=models.CASCADE)
# aprendiz = models.ForeignKey(Student, verbose_name='aprendiz ', related_name='respostaAprendiz', on_delete=models.CASCADE)

created_at = models.DateTimeField('Criado em', auto_now_add=True)
updated_at = models.DateTimeField('Atualizado em', auto_now=True)


def __str__(self):
    return self.edp.titulo + " - " + self.aprendiz.username

def iniciar(self):
    self.save()
@models.permalink
def get_absolute_url(self):
    return ('edp:detalhe_edp_resposta', (), {'slug': self.slug})

class Meta:
    verbose_name = 'Resposta Estrutura Digital de Aprendizagem'
    verbose_name_plural = 'Resposta Estrutura Digital de Aprendizagem'
    ordering = ['-created_at']

class User(AbstractUser):
eh_aluno = models.BooleanField(default=False)
eh_professor = models.BooleanField(default=False)

这是用户的型号:

 class User(AbstractUser):
    eh_aluno = models.BooleanField(default=False)
    eh_professor = models.BooleanField(default=False)

class Student(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

    def __str__(self):
        return self.user.username

0 个答案:

没有答案