Reputation: 37
I have the following models:
class Contactnumber(TimeStampedModel):
phone_number = models.CharField(max_length=100, unique=True)
contact = models.ForeignKey(‘contacts.Contact')
class Contact(TimeStampedModel):
contact = models.CharField(max_length=100, db_index=True,
verbose_name='Contact Name')
practice = models.ManyToManyField(‘practice.Practice’,
related_name=“contacts",)
class Practice(TimeStampedModel):
practice = models.CharField(max_length=150, db_index=True,
verbose_name='Practice Name')
I have a template including data tables in which I want to show the following: Practice, Contact, Contact Phone
The following gives me the contact for the practice:
{% for contact in practice.contacts.all %}
{{ contact }}
{% endfor %}
My question is how do include the contact phone number as I seem a bit lost. Any help would be appreciated. Apologies if this is a simple question!
Upvotes: 0
Views: 43
Reputation: 3482
ATM your contacts can have multiple phone numbers, so one way would be to do it like this:
{% for contact in practice.contacts.all %}
{% for number in contact.contactnumber_set.all %}
{{ number.phone_number }}
{% endfor %}
{% endfor %}
The logic behing this is that when you haven't set a related_name
to a relation field (one2one, FK, M2M), then you can access the related model by the model's name and adding "_set" to the end. So you iterate over all contacts and over all numbers that a contact has and the output will be all the numbers for those guys. Feel free to format it any way you like (adding commas, <br>
's and so on).
Upvotes: 2