I am trying to dynamically populate some paragraph tags with information from my database. I would like each paragraph tag to be in a format like the following <p>Insurances: BCBS, Aetna, Molina</p>
where the BCBS, Aetna, Molina are insurances associated with a given therapist in my database.
In my models, I have Therapist and Insurance classes that are defined by a many-to-many relationship as follows:
class Therapist(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
license_type = models.CharField(max_length=50)
active = models.BooleanField(default=True)
certifications = models.ManyToManyField(Certification)
insurances = models.ManyToManyField(Insurance)
populations = models.ManyToManyField(Population)
bio = models.TextField()
picture = models.ImageField(upload_to="static/bio_pics", default=None)
def __str__(self) -> str:
return f"{self.first_name} {self.last_name}, {self.license_type}"
class Insurance(models.Model):
name = models.CharField(max_length=50)
def __str__(self) -> str:
return self.name
My template code so far is below, with the relevant section being the <p class="insurances>
part of the code:
{% for therapist in therapists %}
<div class="therapist">
<img class="bio-pic"
alt="{{ therapist.first_name }} {{ therapist.last_name }} smiling at the camera."
src="{{ therapist.picture }}" />
<h3 class="therapist-name">{{ therapist.first_name }} {{ therapist.last_name }}, {{ therapist.license_type }}</h3>
<p class="insurances">
Insurance:
{% for insurance in therapist.insurances.all %}<strong>{{ insurance.name }}</strong> |{% endfor %}
</p>
<a class="therapist-link" href="/{{ therapist.id }}">Learn more about {{ therapist.first_name }}</a>
</div>
{% endfor %}
What I would like to be able to do is get a list of strings with all of the insurances for each therapist so that I could do something like {{ therapist.insurances.all|join: ", " }}
but that code obviously fails.
Is there a way to get a list of strings with names of every insurance a therapist has or do I need to take a different approach to accessing that information?