Mauricio
Mauricio

Reputation: 93

I want make a query in django opposing of where?

E.g I have the models

class Question(models.Model):
    question = models.CharField(max_length="200")

class Answer(models.Model):
    question= models.ForeignKey(Question)

So, I want all Question's that I don't have in Answers

E.g In answer I have

Question 1
Question 2

and in Question I have

Question 1
Question 2
Question 3
Question 4

and I want like result of my Query Question 3 and Question 4

thanks

Upvotes: 0

Views: 66

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239240

I think what you want is:

unanswered_questions = Question.objects.filter(answer__isnull=True)

Upvotes: 6

Manfre
Manfre

Reputation: 1245

The easiest way is to first get a distinct list of all question IDs in Answer, then get all Questions that do not have one of those IDs

ids = Answer.objects.all().distinct().values_list('question', Flat=True)
unanswered = Question.objects.all().exclude(pk__in=ids)

Upvotes: 0

Related Questions