Django queries Related Objects

Asked

Viewed 22 times

0

So with two models created :

class Questao(models.Model):
    texto = models.CharField(max_length=220)
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

    def __str(self):
        return str(self.text)

    def get_answers(self):
        return self.resposta_set.all()

    class Meta :
        verbose_name = "Questão"
        verbose_name_plural = "Questões"


class Resposta(models.Model):
    texto = models.CharField(max_length=220)
    correto = models.BooleanField(default=False)
    questao = models.ForeignKey(Questao, on_delete=models.CASCADE, related_name="respostas")
    created = models.DateTimeField(auto_now_add=True)

the function I created to relate both "get_answers" objects is with a visible error

in get_answers
    return self.resposta_set.all()
AttributeError: 'Questao' object has no attribute 'resposta_set'
```
Podem me explicar como funciona o **_set** no django, e por que essa função não retorna nenhum atributo por favor ?

2 answers

0

By your question I note that you would like to list the answers to a question in the get_answers method, so I understand that it should be something like this:

def get_answers(self):
    return Resposta.objects.filter(questao=self)

-1

Another solution would be this:

def get_answers(self):
    return self.respostas.all()

Uses the defined related_name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.