[英]Django reserve foreign key in views
我在模板中有一個反向查詢,該模板處理與外鍵連接在一起的兩個表。 該查詢正在提供我現在想要的結果,但是在將來,很明顯,這將使我遇到關於查詢優化的嚴重問題。 我正在向數據庫發送與正在使用的表相關的所有圖片的查詢,而不是僅顯示其中一張。
我無法適應我在HTML模板中編寫的反向查詢的視圖功能。
在models.py中
class EtkinlikModel(models.Model):
...
class FotografModel(models.Model):
etkinlik = models.ForeignKey(EtkinlikModel, on_delete=models.CASCADE)
在views.py中
def EtkinlikView(request):
etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4]
template = “…”
context = {
"pageName": title,
"etkinlikler" : etkinlikler
}
return render(request,template,context)
在template.html中
{% for etkinlik in etkinlikler %}
{{ etkinlik.etkinlik_adi }}
{% for foto in etkinlik.fotografmodel_set.all|slice:":1" %}
{{ foto.foto }}
{% endfor %}
{% endfor %}
views.py
def EtkinlikView(request):
etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4]
for etkinlik in etkinlikler:
foto = etkinlik.fotografmodel_set.all()
template = “…”
context = {
"pageName": title,
"etkinlikler" : etkinlikler,
"foto":foto
}
return render(request,template,context)
在template.html中
{% for etkinlik in etkinlikler %}
{{ etkinlik.etkinlik_adi }} {{ etkinlik.id }}
{% for f in foto %}
{{f.foto}}
{% endfor %}
{% endfor %}
每個etkinlik對象中僅重復顯示一次foto的結果
def EtkinlikView(request):
etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4]
template = "…"
context = {
"pageName": title,
"etkinlikler" : etkinlikler,
}
return render(request,template,context)
在模板中
{% for etkinlik in etkinlikler %}
{{ etkinlik.etkinlik_adi }} {{ etkinlik.id }}
{{ etkinlik.fotografmodel_set.first.foto }}
{% endfor %}
希望這會工作
在模板中:
{% for etkinlik in etkinlikler %}
{{ etkinlik.etkinlik_adi }} {{ etkinlik.id }}
{{ etkinlik.fotografmodel_set.first.foto }}
{% endfor %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.