我想在 html 中執行類似下面的操作,其中顯示多個“點”,并在每個點內顯示與每個特定點關聯的“鏈接”。
我將如何撰寫邏輯來顯示每個點的特定鏈接?
html
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
{% for link in links %}
<div>
<h3>{{ link.url }}</h3>
</div>
{% endfor %}
{% endfor %}
我的模型如下。SpotLinks 是 Links 和 Spots 表的中間表。
models.py
class Spots(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
class Links(models.Model):
title = models.CharField(unique=True, max_length=155, blank=True)
url = models.CharField(max_length=75, blank=True)
class SpotLinks(models.Model):
link = models.ForeignKey('Links', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
class Articles(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
summary = models.TextField(blank=True, null=True)
class ArticleSpots(models.Model):
article = models.ForeignKey('Articles', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
我links = Links.objects.filter(spotlinks__spot=spots)在 views.py 中嘗試過,但是因為斑點中有多個斑點,所以它沒有被過濾。
邏輯會寫在views.py中還是html檔案中的django模板中?
我是網路開發的新手,所以任何方向都會有所幫助。謝謝!
views.py
def article(request, slug):
article = get_object_or_404(Articles, slug=slug)
spots = Spots.objects.filter(articlespots__article=article).distinct()
links = Links.objects.filter(spotlinks__spot=spots)
context = {
'spots': spots,
'article': article,
'links': links}
return render(request, 'articletemplate.html', context)
uj5u.com熱心網友回復:
您需要在 Links 模型中添加一個外部欄位以參考點,因此 Links 模型將是:
class Links(models.Model):
title = models.CharField(unique=True, max_length=155, blank=True)
url = models.CharField(max_length=75, blank=True)
spot = models.ForeignKey(Spots, on_delete=models.CASCADE, related_name="links")
因此,您可以通過以下方式獲取每個景點的鏈接:
from django.shortcuts import get_object_or_404
spot = get_object_or_404(Spots, title="choose the the title") # you can filter it in your preferred way
links = spot.links.all()
然后,在背景關系中;您根本不需要發送鏈接,而是可以通過這種方式在 html 中進行迭代:
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
{% for link in spot.links %}
<div>
<h3>{{ link.url }}</h3>
</div>
{% endfor %}
{% endfor %}
uj5u.com熱心網友回復:
要訪問相關物件,請使用相關管理器。
在這種情況下,相關經理是spot.spotlinks_set。
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
<!-- {% for link in links %} --> <!-- Replace this -->
{% for spotlink in spot.spotlinks_set.all %} <!-- with this -->
<div>
<!-- <h3>{{ link.url }}</h3> --> <!-- Replace this -->
<h3>{{ spotlink.link.url }}</h3> <!-- with this -->
</div>
{% endfor %}
{% endfor %}
參考:https : //docs.djangoproject.com/en/3.2/ref/models/relations/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343157.html
標籤:Python 姜戈 django-models django-views django-模板
下一篇:CTRL C不會殺死C腳本
