2013-09-26 136 views
0

我有以下型號:如何在Django中顯示多對多關係的元素?

class Topic(models.Model): 
    title = models.CharField(max_length=140) 

    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和它們之間
  • 連接(TopicLabelConnection)。

一個標籤可以分配給很多主題。

我想顯示與以下結構的有序列表:

  1. 標籤1
    1. 主題1
    2. 主題2
    3. 主題3
  2. 標籤2
    1. 主題4
    2. 主題5
    3. 主題6

其中主題1,2和被分配給標籤1和主題4,5和6 - 標記2.

爲了做到這,我創建瞭如下所示的視圖函數和HTML模板片段。

View功能

def home(request):  
    labels = TopicLabel.objects.filter(connection_label__isnull=False).distinct().order_by('order') 

    return TemplateResponse(request, 'home.tpl.html', locals()) 

模板片段

<ol> 
    {% for cur_label in labels %} 
     <li>{{ cur_label.name }}</li> 
     <ol> 
     {% for cur_topic_label_connection in cur_label.getTopics %} 
      <li>{{ cur_topic_label_connection.topicId.title }}</li> 
     {% endfor %} 
     </ol> 
    {% endfor %}  
</ol> 

結果:只有標籤顯示,但不是他們的主題。

我該如何更改代碼才能使標籤和主題顯示在分層列表中?

回答

1

您應該使用合適的多對多場:

class TopicLabel(models.Model): 
    ... 
    topics = models.ManyToManyField(Topic, through=TopicLabelConnection) 

現在您的getTopics方法可以刪除,並在模板你可以做:

{% for topic in cur_label.topics.all %} 
    <li>{{ topic.title }}</li> 
{% endfor %} 

注意,order_by呼叫getTopics是沒有意義的,因爲這有一個order場的唯一模式是TopicLabel,但你正在試圖獲得主題,它沒有秩序領域。

+0

謝謝。現在一個非常愚蠢的問題 - 我怎樣才能定義'ManyToManyField(...,通過= TopicLabelConnection)'沒有像'NameError:名稱'TopicLabelConnection'未定義'錯誤? 'TopicLabel'和'TopicLabelConnection'互相引用。 –

+0

更改TopicLabelConnection。改爲使用字符串'TopicLabelConnection'。 Topics = models.ManyToManyField(Topic,through ='TopicLabelConnection') – Alvaro

+0

我想通了 - '通過'參數需要放在單引號中('topics = models.ManyToManyField(Topic,through ='TopicLabelConnection')') 。 –

1

您沒有正確過濾。

的問題是在getTopics方法

試試這個:

return TopicLabelConnection.objects.filter(labelId__id=self.id).order_by('order') 

通知labelId是TopicLabel,而不是它的id

+0

我試過你的建議,但沒有任何改變。 –

+0

可能你應該使用相關的名字。嘗試刪除它們,看看是否是問題所在。我想不出別的,對不起 – Alvaro