[英]Get an attribute in a template from a ManyToMany relationship in Django
在我的Django 1.5項目中,兩個模型之間存在多對多關系:
class File(models.Model):
#..
subject = models.ManyToManyField(Subject)
class Subject(models.Model):
subject = models.CharField(max_length = 30, primary_key=True, blank=False, null=False)
我想要做的就是知道文件,然后訪問我的HTML模板中的主題。
當然{{ file.subject }}
不起作用。 我知道{{ file.subject.subject }}
是可以循環的查詢集,但是即使嘗試,我也不知道如何獲取正確的Subject
對象。
有一種方法只能通過模板來完成嗎? 還是最好從視圖中傳遞它?
嘗試join
模板標簽:
{{ file.subject.all|join:", " }}
或循環:
{% for subj in file.subject.all %}
{{ subj }}<br/>
{% endfor %}
將有0個或更多的科目; 如果您只想循環,請使用for
塊遍歷file.subject.all()
:
{% for subject in file.subject.all %}
{{ subject.subject }}
{% empty %}
Sorry, no subjects found.
{% endfor %}
如果需要查找特定主題,則必須進行查詢。 在視圖中這樣做; 像這樣的邏輯應該留給Python代碼:
subject = file.subject.filter(subject__startswith='Foo').first()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.