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