Reputation: 191
I have an issue with the output of a ManyToMany query in Django
I have two classes: Investor and Fund. A Fund can have many Investors, and an Investor can be invested in multiple Funds, hence the Manytomany relationship
The objective is to show in HTML (via a template) a list per investor of all the funds in which he/she is invested.
Models.py:
class Fund(models.Model):
name = models.CharField(max_length=100)
def __str__ (self):
return self.name
class Investor(models.Model):
first_name = models.CharField(max_length = 100)
investments = models.ManyToManyField(Fund)
def __str__ (self):
return self.first_name
view.py:
def investors_overview(request):
investors = Investor.objects.all()
return render(request, 'funds/investors.html', {'investors_overview' : investors })
template:
{% for investor in investors_overview %}
<p>{{investor.first_name}} </p>
<p>{{investor.investments.all}} </p>
I would like the have as output the exact names of the various funds the investor is invested in. However, the output in HTML is not "clean" and is as as follows:
<QuerySet [<Fund: Fund1>, <Fund: Fund2>]>
Upvotes: 2
Views: 340
Reputation: 476614
You can iterate over the fund
s, like:
{% for investor in investors_overview.all() %}
<p>{{investor.first_name}} </p>
<p>
{% for fund in investor.investments %}
{{ fund }}
{% endfor %}
</p>
{% endfor %}
You can boost performance of the queryset, by using a .prefetch_related(..)
:
def investors_overview(request):
investors = Investor.objects.prefetch_related('investments')
return render(request, 'funds/investors.html', {'investors_overview' : investors })
Upvotes: 1