python - Insert separator only if didn’t insert one before -
i have template variable product_list
, queryset
of product
objects; product
objects, in turn, have one-to-many field of track
objects (reverse mapped track
, of course), possible empty. want create list of track
s, grouped product
s this:
{% product in product_list %} {% if not first product tracks %} <li class="separator"></li> {% endif %} {% track in product.tracks %} <li>{{track}}</li> {% endfor %} {% endfor %}
the question is, should write of if not first product tracks
? tried ifchanged product
inserts separator on first iteration (as changes ""
"someproduct"
). forloop.counter
not usable here, possible first 2 products won’t have tracks.
one workaround change product_list
track_list
this:
track_list = track.objects.order_by('product__name')
so can indeed use ifchanged
. doable in case, i’m still interested in solution first method.
you should compose condition. looks simple, perhaps not asking for.
{% product in product_list %} {% if not forloop.first , product.tracks %} <li class="separator"></li> {% endif %} {% track in product.tracks %} <li>{{track}}</li> {% endfor %} {% endfor %}
if not solution you, suggest cook data on view , send ready parse template, more easy.
{% product in product_list %} {% if product.should_have_separator %} <li class="separator"></li> {% endif %} {% track in product.tracks %} <li>{{track}}</li> {% endfor %} {% endfor %}
in view append should_have_separator
field dynamically products should have it:
product_list = product.objects..... is_the_first_product = true product in product_list: is_the_first_product_with_tracks = ( is_the_first_product , bool( product.tracks ) ) product.should_have_separator = not is_the_first_product_with_tracks is_the_first_product = false
Comments
Post a Comment