Self
Self

Reputation: 537

which query to be used in data base

For the quiz app, I am having the following model

class Question(models.Model):
  question_id=models.IntegerField(default=0)
  question_text=models.CharField(max_length=1000)

  def __str__(self):
    return self.question_text


class Options(models.Model):
  question=models.ForeignKey(Question,on_delete=models.CASCADE)
  options=models.CharField(max_length=500)
  is_answer=models.BooleanField(default=False)

  def __str__(self):
    return self.options

Only one option for each question is Set to True. I need to find the option of the question which is having the is_answer field is set to True. Which is the best query here? I am using Sqlite. Thank You.

Upvotes: 0

Views: 30

Answers (1)

Evans Murithi
Evans Murithi

Reputation: 3267

You can do:

# Get a Question instance. Your implementation may be different. 
question = Question.objects.get(pk=question_pk)
correct_option = question.options_set.filter(is_answer=True).first()

Doing question.options_set.filter(is_answer=True) returns a queryset of Options instances that have a FK to the question instance so doing .first() returns the first instance in the queryset.

You can also get a particular option (given "Only one option for each question is Set to True"):

try:    
    question.options_set.get(is_answer=True)
except Options.DoesNotExist:
    raise

Upvotes: 1

Related Questions