检查查询是否不存在或具有特定值

时间:2015-06-28 09:58:14

标签: python django django-models django-views

例如,我们有示例模型,我们想要执行以下操作:

ex = Example.objects.filter(Q(participant__tries=0) | Q(participant__tries=*THERE IS NO EXAMPLE RECORD*), courses=course)

我的意思是数据库中没有记录,没有记录并且为空。并且有一个永远不会返回任何对象的查询集。

我们应该在两颗星之间取代什么?

附录:

我自己的模特

class Questions(models.Model):
    course = models.ForeignKey(Course, blank=False, db_index=True)
    question_author = models.ForeignKey(Author, blank=False)
    number = models.IntegerField(default=0, editable=False, help_text="<b>***Please Don't change it as much as possible!</b>")
    question_details = models.CharField(max_length=100, blank=False, default='')
    members = models.ManyToManyField(User, through='QuestionsParticipant')
    question_type = models.CharField(choices=question_types, max_length=1, default='1')
    own_score = models.PositiveIntegerField(default=10)
    approved = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

class QuestionsParticipant(models.Model):
    question = models.ForeignKey(Questions)
    participant = models.ForeignKey(User)
    tries = models.PositiveIntegerField(blank=False, default=0)
    flag = models.BooleanField(default=False)
    flag_reason = models.CharField(max_length=50, blank=True, default='')
    success = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

在我看来:

question = Questions.objects.filter(Q(questionsparticipant__tries=0) | Q(questionsparticipant__tries__isnull=True),
                                                Q(questionsparticipant__participant_id=request.user.id)
                                                | Q(questionsparticipant__participant_id__isnull=True),
                                                course=courses, approved=True).order_by("number")[0]

1 个答案:

答案 0 :(得分:0)

取决于您的模型/架构的设置方式。您可能需要提供其他详细信息。

在许多情况下,isnull会起作用。例如,Q(participant__tries__isnull=True)。请参阅official docs on isnull