简体   繁体   English

从Django中的ManyToMany关系中获取模板中的属性

[英]Get an attribute in a template from a ManyToMany relationship in Django

In my Django 1.5 project I have a many-to-many relationship between two models: 在我的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)

What I want to do is, knowing the file, access to the subject in my HTML templates. 我想要做的就是知道文件,然后访问我的HTML模板中的主题。

Of course {{ file.subject }} doesn't work. 当然{{ file.subject }}不起作用。 I know that {{ file.subject.subject }} it's a query set that can be looped but, even if I try, I don't know how I can grab the right Subject object. 我知道{{ file.subject.subject }}是可以循环的查询集,但是即使尝试,我也不知道如何获取正确的Subject对象。

Is there a way to do it only from templates? 有一种方法只能通过模板来完成吗? Or it's best to pass it from the view? 还是最好从视图中传递它?

Try join template tag: 尝试join模板标签:

{{ file.subject.all|join:", " }}

or loop: 或循环:

{% for subj in file.subject.all %}
     {{ subj }}<br/>
{% endfor %}

There will be 0 or more subjects; 将有0个或更多的科目; if you just want to loop, do so with a for block over file.subject.all() : 如果您只想循环,请使用for块遍历file.subject.all()

{% for subject in file.subject.all %}
    {{ subject.subject }}
{% empty %}
    Sorry, no subjects found.
{% endfor %}

If you need to find a specific subject, you'll have to query for it. 如果需要查找特定主题,则必须进行查询。 Do so in the view; 在视图中这样做; logic like this should be left to Python code: 像这样的逻辑应该留给Python代码:

subject = file.subject.filter(subject__startswith='Foo').first()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM