1👍
✅
### 1st solution (similar to Daniel Rosenthal's answer but with performances concern)
results = DressSizeAvailable.objects.filter(dress__price__lt=50).select_related('dress', 'size')
# then you can browse your DressSizeAvailables as you wish in your template. The select related allows you NOT TO query the database again when you generate your template
### 2nd solution
results = Dress.objects.filter(price__lt=50).prefetch_related('dresssizeavailable_set__dress')
{% for dress in results %}
{{ dress.name }}, ${{ dress }}
Sizes: <ul>
{% for dsa in dress.dresssizeavailable_set %}
<!-- Thanks to the prefetch_related, we do not query the base again here -->
<li>{{ dsa.size.code }}</li>
{% endfor %}
</ul>
{% endfor %}
0👍
You’ll need to give your template a queryset (or something similar) of DressSizeAvailable
objects. So first you’ll need to get all the Dress
objects you’re interested, and then filter DressSizeAvailable
based on those Dresses
so in your view:
dresses = Dress.objects.filter(price__lt=50)
dress_size_available = []
for dress in dresses:
available = DressSizeAvailable.objects.filter(dress=dress)
dress_size_available.append(available)
Then render your template, passing it the variable dress_size_available
Your template can then be rather simple.
{% for dsa in dress_size_available %}
{{ dsa.dress.name }}, ${{ dsa.dress.price }}
Size: {{ dsa.size }}
{% endfor %}
Source:stackexchange.com