我有以下型號:如何在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
- 主題2
- 主題3
- 標籤2
- 主題4
- 主題5
- 主題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>
結果:只有標籤顯示,但不是他們的主題。
我該如何更改代碼才能使標籤和主題顯示在分層列表中?
謝謝。現在一個非常愚蠢的問題 - 我怎樣才能定義'ManyToManyField(...,通過= TopicLabelConnection)'沒有像'NameError:名稱'TopicLabelConnection'未定義'錯誤? 'TopicLabel'和'TopicLabelConnection'互相引用。 –
更改TopicLabelConnection。改爲使用字符串'TopicLabelConnection'。 Topics = models.ManyToManyField(Topic,through ='TopicLabelConnection') – Alvaro
我想通了 - '通過'參數需要放在單引號中('topics = models.ManyToManyField(Topic,through ='TopicLabelConnection')') 。 –