How to select only questions not yet answered by a user in Django

妖精的绣舞 提交于 2019-12-14 04:19:49

问题


I am creating a quiz and would like to show to the user only questions that were not answered by himself. How do I do that?

models.py

class Questao(models.Model):
    idQuestao = models.CharField(
        max_length=7,
        primary_key=True,
        null=False,
        verbose_name="ID da questão")

class Resposta(models.Model):
    idQuestao = models.ForeignKey(
        Questao,
        on_delete=models.CASCADE,
        verbose_name="ID da questão")
    usuario = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name="Usuário")

views.py

questao = Questao.objects.filter(tipoQuestao=1, resposta__usuario=request.user)\
    .exclude(idQuestao=Resposta.objects.filter())\
    .order_by("?")\
    .first()

EDIT

When I enter the quiz, I was asked the question E200501 to answer, but the one that was answered was the E200503.


回答1:


To exclude questions were the user has answered already I would suggest using .annotate() with Count (and maybe even Case/When) to count the related items in a single query and filter them out.

from django.db import models

questao = Questao.objects\
    .annotate(
        resp_count=models.Count(
            models.Case(
                models.When(resposta__usuario=request.user, then=1),
                output_field=models.IntegerField())))\
    .filter(tipoQuestao=1, resp_count=0)\
    .order_by("?")\
    .first()

Would this work for you?




回答2:


I assume that whenever user answers to a question Resposta object is created if you simply want to return the Questao that user has not answered yet you just need exclude()

questao = Questao.objects.exclude(resposta__usuario=request.user)


来源:https://stackoverflow.com/questions/58287955/how-to-select-only-questions-not-yet-answered-by-a-user-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!