Django - multiple models in one view
I have scoured the StackOverflow pages and none of the solutions to this problem are working for me. I have two models in the same app and am trying to display data from both models in the same template using class based DetailView.
This is my code, but the only thing that displays is the data from the Project model.
models.py
from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=100)
project_location = models.CharField(max_length=100)
def __str__(self):
return self.project_name
class Well(models.Model):
project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
well_name = models.CharField(max_length=100)
def __str__(self):
return self.well_name
views.py
class ProjectDetailView(DetailView):
model = Project
template_name = 'project/project_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['projects'] = Project.objects.all()
context['wells'] = Well.objects.all()
return context
html
{{ project.project_name}} {{ well.well_name}}
What am I missing? The Django docs for DetailView only show how to display data from one model, not two.
You don't need to add anything extra to the context, you can work with:
{{ project.project_name }}
{% for well in project.well_set.all %}
{{ well.well_name }}
{% endfor %}