0

我有以下 Django 模型:

class TopicLabel(models.Model):
    name = models.CharField(max_length=256)
    order = models.IntegerField(null=True, blank=True)
    topics = models.ManyToManyField(Topic, through='TopicLabelConnection')

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

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

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,它将返回TopicLabel.topic集合中的所有主题,其中包含Topic.visible = True.

我想编写与以下查询等效的 Django:

SELECT *
FROM OPINIONS_TOPICLABELCONNECTION, OPINIONS_TOPIC
WHERE (OPINIONS_TOPICLABELCONNECTION.topicId_id = OPINIONS_TOPIC.id) AND
    (OPINIONS_TOPICLABELCONNECTION.labelId_id = X) AND 
    (OPINIONS_TOPIC.visible = 1)

其中X是主题标签的主键。

我尝试了以下方法定义,但都失败了:

1)

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics():
        return topics.filter(connection_topic__visible=True)

2)

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics():
        return topics.filter(visible=True)

3)

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics():
        return Topic.objects.filter(connection_label__visible=True).filter(connection_label__id=self.id)

4)

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics():
        return Topic.objects.filter(connection_label__visible=True).filter(connection_label__id=self.id)

5)

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics():
        return topics.filter(connection_topicId__visible=True)

什么是正确的代码?

4

1 回答 1

2

首先,您需要将其self作为方法的第一个参数。然后过滤主题。尝试这个:

class TopicLabel(models.Model):
    [...]
    def getVisibleTopics(self):
        return self.topics.filter(visible=True)

另外,您创建自定义直通表是否有原因?看起来您没有向其中添加任何额外数据。

于 2013-10-02T20:38:25.180 回答