1
Iโm not overly familiar with Django and Python anymore, but I guess you could do a preliminary check to see if there are damages with or without images in there.
damages_with_images = [d for d in damages if d.images.length > 0]
damages_without_images = [d for d in damages if d.images.length == 0]
And then just loop over these two separate arrays, and only print the heading if they are not emptyโฆ
{% if damages_with_images|length > 0 %}
put heading1
{% endif %}
# ... loop ...
{% if damages_without_images|length > 0 %}
put heading2
{% endif %}
# ... loop ...
Of course this has worse performance because of multiple loops.
0
What I would do in your position is
-
Either pass two separate
QuerySet
s in the template, the first would include damages with images and the other damages without images. -
Leave the
QuerySet
as is and create two custom template filters that would do the same job as the step #1 above.
Case 1:
# views.py
def my_view(request):
damages_w_img = Damage.objects.filter(images__isnull=False)
damages_wo_img = Damage.objects.filter(images__isnull=True)
return render(request, 'template.html', locals())
<!-- template.html -->
{% if damages_w_img.exists %}
<h1>This list of damages contains images</h1>
{% for damage in damages_w_img %}
do stuff here, each damage has an image
{% endfor %}
{% endif %}
{% if damages_wo_img.exists %}
<h1>This list of damages does not contain images</h1>
{% for damage in damages_wo_img %}
do stuff here, each damage does not has an image
{% endfor %}
{% endif %}
Case 2:
# custom_template_filter.py
from django import template
register = template.Library()
@register.filter
def with_images(damages):
return damages.objects.filter(images__isnull=False)
@register.filter
def without_images(damages):
return damages.objects.filter(images__isnull=True)
<!-- template.html -->
{% with damage_w_img=car.damages|with_images damage_wo_img=car.damages|without_images %}
{% if damages_w_img.exists %}
<h1>This list of damages contains images</h1>
{% for damage in damages_w_img %}
do stuff here, each damage has an image
{% endfor %}
{% endif %}
{% if damages_wo_img.exists %}
<h1>This list of damages does not contain images</h1>
{% for damage in damages_wo_img %}
do stuff here, each damage does not has an image
{% endfor %}
{% endif %}
{% endwith %}
- How to use MultipleChoiceField in django-widget-tweaks?
- How to increment a variable in another script through importing?
- Django 1.10.6 Limiting Querysets to return lastly entered records?
- How do I 'cleanly' create this Django/DRF serialization relationship between models?
- Load CSV values then search for matches in mysql database and then apply insertion?
Source:stackexchange.com