Django:使用EXISTS或子查询进行查询

时间:2013-09-30 09:44:05

标签: python django django-models

我有以下模特:

class Topic(models.Model):
    title = models.CharField(max_length=140)
    visible = models.NullableBooleanField(null=True, blank=True, default=False)

    def __unicode__(self):
        return self.title
    class Meta:
        verbose_name = _('topic')
        verbose_name_plural = _('topics')

class TopicLabel(models.Model):
    name = models.CharField(max_length=256)
    order = models.IntegerField(null=True, blank=True)

    def getTopics():
        return TopicLabelConnection.objects.filter(labelId=self.id).orderby('order')

    def __unicode__(self):
        return self.name


class TopicLabelConnection(models.Model):
    topicId = models.ForeignKey(Topic, related_name='connection_topic')
    labelId = models.ForeignKey(TopicLabel, related_name='connection_label')

    def __unicode__(self):
        return self.labelId.name + ' / ' + self.topicId.title

每个主题都可以显示。

我需要编写一个查询,它返回所有至少有一个可见主题的TopicLabel。

是否可以在不使用extra函数的情况下在Django中创建此类查询(将SQL注入到Django代码中)?如果是,怎么样?

1 个答案:

答案 0 :(得分:1)

使用TopicLabel.objects.filter(connection_label__topicId__visible=True)

示例会话:

>>> t1 = Topic.objects.create(title='visible1', visible=True)
>>> t2 = Topic.objects.create(title='visible2', visible=True)
>>> t3 = Topic.objects.create(title='invisible1', visible=False)
>>> t4 = Topic.objects.create(title='invisible2', visible=False)
>>> tl1 = TopicLabel.objects.create(name='1')
>>> tl2 = TopicLabel.objects.create(name='2')
>>> tl3 = TopicLabel.objects.create(name='3')
>>> TopicLabelConnection.objects.create(topicId=t1, labelId=tl1) 
>>> TopicLabelConnection.objects.create(topicId=t2, labelId=tl2) 
>>> TopicLabelConnection.objects.create(topicId=t3, labelId=tl3) 
>>> TopicLabelConnection.objects.create(topicId=t4, labelId=tl3) 

>>> TopicLabel.objects.filter(connection_label__topicId__visible=True)
[<TopicLabel: 1>, <TopicLabel: 2>]