I have this code
{% for account in object_list %}
{% for field, value in book.get_fields %}
{{ field.v
-
I found a way to do this with a condition. It's ugly and hacky, but it works (for me). first is what the OP wanted, but this answers the actual question more closely.
Given this:
obj = {
'children': [
{ 'possessions' : { 'toys': [] } },
{ 'possessions' : { 'toys': ['train'] } }
{ 'possessions' : { 'toys': ['train', 'ball'] } }
]
}
I wanted to know if my obj has any children with possessions that are toys.
Here's what I did:
Python Equivalent:
if ([child for child in obj.children if child.possessions.toys]):
# Whatever
Django Template:
My approach was to use regroup to build sets of candidates which did or didn't match the criteria:
{% regroup obj.children by possessions.toys|length_is:"0" as by_toys %}
{% for check in by_toys %}{% if check.grouper == False %}
Whatever
{% endif %}{% endfor %}
regroup builds a new object that is essentially:
[
{ 'grouper': '', 'list': [/*...*/] },
{ 'grouper': True, 'list': [/*...*/] },
{ 'grouper': False, 'list': [/*...*/] }
]
The length_is:"0" makes sure that we have at most three elements in that list and the grouper is either True or False or ''. Then we iterate over the list and check for a False value.
- If there are no children it'd be an empty list and the
if would never be hit.
- If no children have toys, it'd be a list without a
False grouper.
- If all children have toys, it'd be a list with a
False grouper.
- If some children have toys, it'd be a list with
False and True groupers.
- 热议问题