排除两个不同的查询集

时间:2017-10-09 06:47:53

标签: django django-models django-views

我正在用django制作一个GK测试界面。在此,一旦提交给用户的问题不应再次出现。 此表存储提交后的所有问题以及与之相关的所有其他数据。

class UserLog(models.Model):
    session = models.ForeignKey(to = UserTestSession, default = None)
    question = models.OneToOneField(to = MCQuestion)
    user = models.ForeignKey(to = User)
    selected_option = models.IntegerField(blank=True,null=True)
    answer_status = models.BooleanField(default = True)     
    quest_submit_time = models.DateTimeField(blank=False)
    ans_submit_time = models.DateTimeField(blank = True,null=True)
    def getDiff(self):
        diff = self.quest_submit_time - self.ans_submit_time
        return divmod(diff.days * 86400 + diff.seconds, 60)
    time_elapsed = property(getDiff)

    def __str__(self):
        return str(self.user) + " " + str(self.question)

    class Meta:
        unique_together = ('question','user',)

class MCQuestion(models.Model):
      question = models.CharField(max_length = 1000,unique = True)
      optA = models.CharField(max_length = 1000)
      optB = models.CharField(max_length = 1000)
      optC = models.CharField(max_length = 1000)
      optD = models.CharField(max_length = 1000)
      right = models.IntegerField(default=1,validators=(MaxValueValidator(4),MinValueValidator(1)))
      category = models.ForeignKey(to = Category,default=None)

      def __str__(self):
          return str(self.question) + " ~ category : " + str(self.category)

我试过这一行来排除。

all_questions = MCQuestion.objects.filter(category = cat.category_id)
submitted_questions = UserLog.objects.filter(user = request.user).values('question_id')
unsubmitted_questions = list(all_questions.exclude(question__in = submitted_questions))

即使这些行包含在我的views.py中,问题也会在前端重复出现。我认为exclude()不能正常工作。

1 个答案:

答案 0 :(得分:0)

对此的一行查询将是

MCQuestion.objects.exclude(userlog__user__isnull=False)

这将为您提供未提交给任何用户的所有MCQuestions。