Cleanest way to get list of Django objects that have same foreign key and display them in a view

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












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:



company_detail_view



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






share|improve this question

























    up vote
    0
    down vote

    favorite












    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:



    company_detail_view



    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






    share|improve this question





















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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:



      company_detail_view



      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






      share|improve this question











      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:



      company_detail_view



      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








      share|improve this question










      share|improve this question




      share|improve this question









      asked May 21 at 22:44









      pavlos163

      1755




      1755




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted











          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()






          share|improve this answer





















            Your Answer




            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );








             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194906%2fcleanest-way-to-get-list-of-django-objects-that-have-same-foreign-key-and-displa%23new-answer', 'question_page');

            );

            Post as a guest






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted











            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()






            share|improve this answer

























              up vote
              1
              down vote



              accepted











              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()






              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted







                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()






                share|improve this answer














                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()







                share|improve this answer













                share|improve this answer



                share|improve this answer











                answered May 24 at 7:52









                James Hiew

                24114




                24114






















                     

                    draft saved


                    draft discarded


























                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194906%2fcleanest-way-to-get-list-of-django-objects-that-have-same-foreign-key-and-displa%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Greedy Best First Search implementation in Rust

                    Function to Return a JSON Like Objects Using VBA Collections and Arrays

                    C++11 CLH Lock Implementation