1

我有以下型号:

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

每个主题都可以可见或不可见。

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

是否可以在 Django 中创建这样的查询而不使用额外的函数(将 SQL 注入 Django 代码)?如果是,如何?

4

1 回答 1

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>]
于 2013-09-30T10:02:24.883 回答