2013-10-02 93 views
0

我有以下Django模型:如何過濾ManyToManyField的記錄?

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) 

什麼是正確的代碼?

回答

3

首先,您需要將self作爲方法的第一個參數。然後過濾主題。試試這個:

​​

此外,是否有你通過表創建自定義的原因?它看起來並不像你正在向它添加任何額外的數據。