Reputation: 444
I'm trying to show information from two models, in a single view in a Django project. I have 2 models: Main (parent), Visits (child) I would like to show a details view of Main (name, date of birth) and then show a list of the Visits. Effectively, show one record from parent table, and all the related children tables. But the children tables are only partially showing up (see the image).
Also, can someone tell me how the Django code knows to render only the child records that are associated with the parent record (where/when are foreign keys filtered?)
eg:
Main.name
views.py
class MainDetailView(generic.DetailView):
model = Main
template_name = "myapp/main-detail.html"
def get_context_data(self, **kwargs):
context = super(MainDetailView, self).get_context_data(**kwargs)
context['visit'] = Visit.objects.all()
# And so on for more models
return context
models.py
class Visit(models.Model):
fk_visit_patient = models.ForeignKey(Main, on_delete=models.CASCADE,
verbose_name=('Patient Name'))
visit_date = models.DateField()
visit_label = models.CharField(max_length=256, blank=True, null=True)
visit_specialty_list = (
(str(1), 'General Practice'),
(str(2), 'Internal Medicine'),
(str(3), 'Surgery'),
visit_specialty = models.CharField(
max_length=256,
choices=visit_specialty_list,
default=1, )
def __str__(self):
return str(self.visit_label)
def get_absolute_url(self):
return reverse('myapp:main-detail', kwargs={'pk': self.pk})
template.html
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="'panel panel-default">
<div class="panel-body">
<h1>{{ main.name }}</h1>
<p><strong>Date of Birth:</strong> <a href="">{{ main.date_of_birth }}</a></p>
<div style="margin-left:20px;margin-top:20px">
<h4>Visits</h4>
{% for visit in main.visit_set.all %}
<li><a href="#">{{ Visit.visit_date }} - {{ Visit.visit_specialty }}</a></li>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 70
Reputation: 599610
You loop defines the variable as visit
, but inside you refer to Visit
. You need to be consistent.
{% for visit in main.visit_set.all %}
<li><a href="#">{{ visit.visit_date }} - {{ visit.visit_specialty }}</a></li>
{% endfor %}
Note, there is no need to pass the Visits separately to the template as you are doing in get_context_data
- you should remove that method completely.
Upvotes: 1