Django 查询自引用多对多关系
我试图获取数据库中所有手稿的列表,打印出每个手稿的架子标记,如果它们链接到其他手稿,还打印出这些手稿的架子标记。
这是我的模型的样子:
class MSS(models.Model):
shelfmark = models.CharField(max_length=50)
MSSLink = models.ManyToManyField('self',through='MSSLink',symmetrical=False)
[...]
class MSSLink(models.Model):
link1 = models.ForeignKey('MSS', related_name='First_MSS')
link2 = models.ForeignKey('MSS', related_name='Second_MSS')
[...]
这是views.py 中的代码
def show_all_MSS(request):
all_MSS = MSS.objects.select_related().all() # get all MSS
t = loader.get_template('list.html')
c = Context({'all_MSS': all_MSS, })
return HttpResponse(t.render(c))
问题是在我的模板中做什么。我想过做这样的事情,但我不知道如何测试 for 循环中的当前 MS 是否已链接到另一个 MS,如果是,如何显示这些架子标记:
{% if all_MSS %}
<ul>
{% for i in all_MSS %}
<li><a href="/MSS/{{ i.shelfmark}}/">{{ i.shelfmark }}</a></li>
{% if i.MSSLink %}
<p>This MS is linked to the following MSS: {{ i.MSSLink.link1 }}</p>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No MSS found</p>
{% endif %}
I am trying to get a list of all manuscripts in my db, print out the shelfmarks for each of them and in case that they are linked to other manuscripts also print out the shelfmarks of those manuscripts.
Here is what my models look like:
class MSS(models.Model):
shelfmark = models.CharField(max_length=50)
MSSLink = models.ManyToManyField('self',through='MSSLink',symmetrical=False)
[...]
class MSSLink(models.Model):
link1 = models.ForeignKey('MSS', related_name='First_MSS')
link2 = models.ForeignKey('MSS', related_name='Second_MSS')
[...]
Here is the code in views.py
def show_all_MSS(request):
all_MSS = MSS.objects.select_related().all() # get all MSS
t = loader.get_template('list.html')
c = Context({'all_MSS': all_MSS, })
return HttpResponse(t.render(c))
The question is then what to do in my template. I thought about doing something like this, but I don't know how I can test whether the current MS in the for-loop has been linked to another MS and if so how to display those shelfmarks:
{% if all_MSS %}
<ul>
{% for i in all_MSS %}
<li><a href="/MSS/{{ i.shelfmark}}/">{{ i.shelfmark }}</a></li>
{% if i.MSSLink %}
<p>This MS is linked to the following MSS: {{ i.MSSLink.link1 }}</p>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No MSS found</p>
{% endif %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的模型有点复杂 - 您可能可以摆脱 MSSLink:
并将其添加到您的模板中:
Your models are a bit complicated - you can probably get rid of MSSLink:
and add this to your template: