I am a beginner in Django and would like some advice regarding best practices.
I have the following model:
class Company(models.Model):
name = models.CharField(max_length=200)
class Interview(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
position = models.CharField(max_length=200)
(I didn't include the __str__
methods for conciseness)
I have the following path:
path('<int:company_id>/', views.detail, name='detail')
Where I want the company to be displayed (let's say its company_id=1
, along with all the interview
objects that have company=1
). So the view should look something like:
Here is my view method:
def detail(request, company_id):
company = get_object_or_404(Company, pk=company_id)
return render(request, 'core/detail.html', {'company': company, 'interviews': Interview.objects.filter(company_id=company_id)})
And my detail.html
file:
<h1>{{ company }}</h1>
<ul>
{% for interview in interviews %}
<li>{{ interview.position }}</li>
{% endfor %}
</ul>
Which works. However, I am not sure if passing the interviews QuerySet
like that is a good practice or not. Is there a way to pass only the company
object and get the interviews from that? In general, is there a better way to get a list of objects that have the same foreign key? In this case for example, would it be possible to instead of doing:
Interview.objects.filter(company_id=company_id)
Doing:
company.interviews
1 Answer 1
However, I am not sure if passing the interviews QuerySet like that is a good practice or not.
This is good practice, known as dependency injection. If someone asks for your business card, you wouldn't give them your wallet and let them fish it out - you can think of passing objects to the template renderer the same way. Passing only the company
object would mean there would have to be more logic in your detail.html
template to fish out the interviews
, which is less than ideal. The way you currently do it serves as documentation as to what objects are required by the detail.html
template.
In general, is there a better way to get a list of objects that have the same foreign key?
You can specify a related_name
for the company
foreign key on your Interview
model like so.
class Company(models.Model):
name = models.CharField(max_length=200)
class Interview(models.Model):
company = models.ForeignKey(Company, related_name='interviews', on_delete=models.CASCADE)
position = models.CharField(max_length=200)
Then you can access all interviews for a company like company.interviews.all()