[英]Django: Check in template if queryset is empty
我已經找到了解決方案,但目前只能通過查看視圖。 我需要檢查模板。
我的觀點:
brands = Brand.objects.all()
for brand in brands:
brand.products = Product.objects.filter(brand=brand.id)
所以在我的模板中,我想展示我所有的品牌,而不是那些沒有任何產品的品牌。
{% for brand in brands %}
{% if brand.product is not None %}
<!-- Displays brand -->
{% endif %}
{% endfor %}
類似的東西,但代碼is not None
不適用於空查詢集,它仍然顯示其中沒有對象的品牌。 我能做些什么?
編輯:按要求共享模型。
class Brand(models.Model):
name = models.CharField(max_length=100, null=False)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, null=False)
brand = models.IntegerField(null=True)
price = models.DecimalField(max_digits=12, decimal_places=2, null=False)
def __str__(self):
return self.name
你的模板應該是這樣的:
{% for brand in brands %}
{% if brand.product %}
<!-- Displays brand -->
{% endif %}
{% endfor %}
使用IntegerField
等來表示關系通常不是一個好主意。 Django 使用ForeignKey
[Django-doc]來實現這種關系。 這樣做有很多好處:(1)它會給數據庫增加額外的約束,使得鍵只能引用一個真實的Brand
; (2) 您將有額外的方法來檢索相關的Product
。
因此Product
模型應該有一個Brand
模型的ForeignKey
,例如:
class Product(models.Model):
name = models.CharField(max_length=100, null=False)
brand = models.ForeignKey(Brand, null=True, db_column='brand')
price = models.DecimalField(max_digits=12, decimal_places=2, null=False)
在這里,我們保持數據庫結構本身不變,但它會在其上添加一個ForeignKey
以及一個index ,從而更快地檢索給定Brand
的所有產品。
在模板中編寫(業務)邏輯通常是一個壞主意。 實際上Django模板語言不允許使用參數等進行調用的原因之一是避免人們在模板中編寫業務邏輯。 所以我強烈建議你將邏輯轉移到視圖上。
您可以使用單線檢索在視圖中至少有一個相關Product
的Brand
:
Brand.objects.filter(product__isnull=False).distinct()
所以沒有必要單獨檢查每個品牌。 在這里,我們還在單個查詢中檢查所有Brand
的Product
的存在,而不是每個Brand
的額外查詢來檢查是否存在相關Product
。
這將產生一個如下所示的查詢:
SELECT DISTINCT brand.*
FROM brand
INNER JOIN product ON brand.id = product.brand_id
WHERE product.id IS NOT NULL
如果您想在集合為空時顯示不同的內容,請查看:
{% for i in list %}
// Do this in non - empty condition
{% empty %}
// Do this in empty condition
{% endfor %}
信用: GeeksForGeeks
這個在我的 for 中使用 {% empty %} 的簡單解決方案對我有用。
{% for detallesblog in object_list %}
<label for="detalles" class="negritatxt">Detalles</label>
<p>
{{ detallesblog.detalles }}
</p>
<label for="logo" class="negritatxt">Logo</label>
<p>
<img src="{% static 'uploads/' %}{{ detallesblog.logo }} " class="img-fluid" alt="{{ detallesblog.logo }}">
</p>
<label for="updated_at" class="negritatxt">Fecha de Actualización</label>
<p>
{{ detallesblog.updated_at }}
</p>
<a href="detallesblog/editar/{{ detallesblog.id }}" title="Editar" type="button" class="btn btn-primary">Editar Datos</a>
{% empty %}
"You have not yet edited the details of your Blog", press the "Edit Data" button to do so.
<
<a href="detallesblog/editar/{{ detallesblog.id }}" title="Editar" type="button" class="btn btn-primary">Editar Datos</a>
{% endfor %}
您可以根據自己的需要進行調整
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.