Django - Having trouble using foreign key model












0














TL;DR Accessing an objects foreign key, invoice must have one customer, how can I show an invoice and it's customer data in HTML Template?



I'm making an invoicing system, so I have these models.



class Customer(models.Model):
name = models.CharField(max_length=100, default='')
email = models.EmailField(max_length=100, default='')
phone_num = models.CharField(max_length=10, default='')
address = models.CharField(max_length=200, default='')

def __str__(self):
return str(self.id)

class Invoice(models.Model):
amount = models.FloatField(max_length=10, default=0)
job_description = models.CharField(max_length=100, default="")
date_of_issue = models.DateField(default='')
customer = models.ForeignKey(Customer, on_delete=models.PROTECT,
related_name='cus')

def __str__(self):
return str(self.job_description + "t$" + str(self.amount))


An Invoice has ONE and ONLY ONE Customer.



I can easily print customers and invoices separately using templates. How can I access the customer which an invoice was sent to?



If I want to look up an invoice, how can I get the customers name and contact details to show in a template?



Currently I have displayed all of my invoices (looping through) and would like to show the customer name and ID number with the invoice information.



How can I then do it backwards and search for all invoices belonging to customer 'x'?










share|improve this question
























  • An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
    – Sachin Kukreja
    Nov 23 '18 at 11:19










  • @SachinKukreja Yep, thanks, I'm new to Django can ya tell.
    – Dan
    Nov 23 '18 at 11:27
















0














TL;DR Accessing an objects foreign key, invoice must have one customer, how can I show an invoice and it's customer data in HTML Template?



I'm making an invoicing system, so I have these models.



class Customer(models.Model):
name = models.CharField(max_length=100, default='')
email = models.EmailField(max_length=100, default='')
phone_num = models.CharField(max_length=10, default='')
address = models.CharField(max_length=200, default='')

def __str__(self):
return str(self.id)

class Invoice(models.Model):
amount = models.FloatField(max_length=10, default=0)
job_description = models.CharField(max_length=100, default="")
date_of_issue = models.DateField(default='')
customer = models.ForeignKey(Customer, on_delete=models.PROTECT,
related_name='cus')

def __str__(self):
return str(self.job_description + "t$" + str(self.amount))


An Invoice has ONE and ONLY ONE Customer.



I can easily print customers and invoices separately using templates. How can I access the customer which an invoice was sent to?



If I want to look up an invoice, how can I get the customers name and contact details to show in a template?



Currently I have displayed all of my invoices (looping through) and would like to show the customer name and ID number with the invoice information.



How can I then do it backwards and search for all invoices belonging to customer 'x'?










share|improve this question
























  • An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
    – Sachin Kukreja
    Nov 23 '18 at 11:19










  • @SachinKukreja Yep, thanks, I'm new to Django can ya tell.
    – Dan
    Nov 23 '18 at 11:27














0












0








0







TL;DR Accessing an objects foreign key, invoice must have one customer, how can I show an invoice and it's customer data in HTML Template?



I'm making an invoicing system, so I have these models.



class Customer(models.Model):
name = models.CharField(max_length=100, default='')
email = models.EmailField(max_length=100, default='')
phone_num = models.CharField(max_length=10, default='')
address = models.CharField(max_length=200, default='')

def __str__(self):
return str(self.id)

class Invoice(models.Model):
amount = models.FloatField(max_length=10, default=0)
job_description = models.CharField(max_length=100, default="")
date_of_issue = models.DateField(default='')
customer = models.ForeignKey(Customer, on_delete=models.PROTECT,
related_name='cus')

def __str__(self):
return str(self.job_description + "t$" + str(self.amount))


An Invoice has ONE and ONLY ONE Customer.



I can easily print customers and invoices separately using templates. How can I access the customer which an invoice was sent to?



If I want to look up an invoice, how can I get the customers name and contact details to show in a template?



Currently I have displayed all of my invoices (looping through) and would like to show the customer name and ID number with the invoice information.



How can I then do it backwards and search for all invoices belonging to customer 'x'?










share|improve this question















TL;DR Accessing an objects foreign key, invoice must have one customer, how can I show an invoice and it's customer data in HTML Template?



I'm making an invoicing system, so I have these models.



class Customer(models.Model):
name = models.CharField(max_length=100, default='')
email = models.EmailField(max_length=100, default='')
phone_num = models.CharField(max_length=10, default='')
address = models.CharField(max_length=200, default='')

def __str__(self):
return str(self.id)

class Invoice(models.Model):
amount = models.FloatField(max_length=10, default=0)
job_description = models.CharField(max_length=100, default="")
date_of_issue = models.DateField(default='')
customer = models.ForeignKey(Customer, on_delete=models.PROTECT,
related_name='cus')

def __str__(self):
return str(self.job_description + "t$" + str(self.amount))


An Invoice has ONE and ONLY ONE Customer.



I can easily print customers and invoices separately using templates. How can I access the customer which an invoice was sent to?



If I want to look up an invoice, how can I get the customers name and contact details to show in a template?



Currently I have displayed all of my invoices (looping through) and would like to show the customer name and ID number with the invoice information.



How can I then do it backwards and search for all invoices belonging to customer 'x'?







python sql django web-applications






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 11:18







Dan

















asked Nov 23 '18 at 11:12









DanDan

10810




10810












  • An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
    – Sachin Kukreja
    Nov 23 '18 at 11:19










  • @SachinKukreja Yep, thanks, I'm new to Django can ya tell.
    – Dan
    Nov 23 '18 at 11:27


















  • An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
    – Sachin Kukreja
    Nov 23 '18 at 11:19










  • @SachinKukreja Yep, thanks, I'm new to Django can ya tell.
    – Dan
    Nov 23 '18 at 11:27
















An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
– Sachin Kukreja
Nov 23 '18 at 11:19




An Invoice has ONE and ONLY ONE Customer. then you should use OneToOneField.
– Sachin Kukreja
Nov 23 '18 at 11:19












@SachinKukreja Yep, thanks, I'm new to Django can ya tell.
– Dan
Nov 23 '18 at 11:27




@SachinKukreja Yep, thanks, I'm new to Django can ya tell.
– Dan
Nov 23 '18 at 11:27












2 Answers
2






active

oldest

votes


















1














ForeignKey in Django are many to one key . If your invoice has only one customer you use should use OneToOneKey instead.But anyways you can access it.



for invoice in Invoice.objects.all():
invoice.customer # to get the model
invoice.customer.name # to get the name field of Customer model


in Template



{% for invoice in invoices %}
{{ invoice.customer.name }}
{% endfor %}


Request



return render(request, 'template_name.html',context={'invoices':Invoice.objects.all()})





share|improve this answer































    1














    You can do it like this:



    for inv in Invoice.objects.all():
    print(inv.custom.name)
    print(inv.custom.email)


    In template:



    {% for inv in invoices %}
    {{ inv.customer.name }}
    {% endfor %}


    And you need to send this information via context like:



    return render(request, 'template.html', { 'invoices': Invoice.objects.all() })


    You need to send the queryset from View to Template. You can use render to do that.



    If you are using a Class Based View, then try like this:



    class SomeListView(ListView):
    model = Invoice
    template = 'your_template.html'


    # template for list view
    {% for inv in object_list %}
    {{ inv.customer.name }}
    {% endfor %}


    See here for more details in ListView






    share|improve this answer



















    • 1




      Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
      – Dan
      Nov 23 '18 at 11:29











    Your Answer






    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: "1"
    };
    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',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445627%2fdjango-having-trouble-using-foreign-key-model%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    ForeignKey in Django are many to one key . If your invoice has only one customer you use should use OneToOneKey instead.But anyways you can access it.



    for invoice in Invoice.objects.all():
    invoice.customer # to get the model
    invoice.customer.name # to get the name field of Customer model


    in Template



    {% for invoice in invoices %}
    {{ invoice.customer.name }}
    {% endfor %}


    Request



    return render(request, 'template_name.html',context={'invoices':Invoice.objects.all()})





    share|improve this answer




























      1














      ForeignKey in Django are many to one key . If your invoice has only one customer you use should use OneToOneKey instead.But anyways you can access it.



      for invoice in Invoice.objects.all():
      invoice.customer # to get the model
      invoice.customer.name # to get the name field of Customer model


      in Template



      {% for invoice in invoices %}
      {{ invoice.customer.name }}
      {% endfor %}


      Request



      return render(request, 'template_name.html',context={'invoices':Invoice.objects.all()})





      share|improve this answer


























        1












        1








        1






        ForeignKey in Django are many to one key . If your invoice has only one customer you use should use OneToOneKey instead.But anyways you can access it.



        for invoice in Invoice.objects.all():
        invoice.customer # to get the model
        invoice.customer.name # to get the name field of Customer model


        in Template



        {% for invoice in invoices %}
        {{ invoice.customer.name }}
        {% endfor %}


        Request



        return render(request, 'template_name.html',context={'invoices':Invoice.objects.all()})





        share|improve this answer














        ForeignKey in Django are many to one key . If your invoice has only one customer you use should use OneToOneKey instead.But anyways you can access it.



        for invoice in Invoice.objects.all():
        invoice.customer # to get the model
        invoice.customer.name # to get the name field of Customer model


        in Template



        {% for invoice in invoices %}
        {{ invoice.customer.name }}
        {% endfor %}


        Request



        return render(request, 'template_name.html',context={'invoices':Invoice.objects.all()})






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 11:27

























        answered Nov 23 '18 at 11:20









        Vivek SinghVivek Singh

        7810




        7810

























            1














            You can do it like this:



            for inv in Invoice.objects.all():
            print(inv.custom.name)
            print(inv.custom.email)


            In template:



            {% for inv in invoices %}
            {{ inv.customer.name }}
            {% endfor %}


            And you need to send this information via context like:



            return render(request, 'template.html', { 'invoices': Invoice.objects.all() })


            You need to send the queryset from View to Template. You can use render to do that.



            If you are using a Class Based View, then try like this:



            class SomeListView(ListView):
            model = Invoice
            template = 'your_template.html'


            # template for list view
            {% for inv in object_list %}
            {{ inv.customer.name }}
            {% endfor %}


            See here for more details in ListView






            share|improve this answer



















            • 1




              Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
              – Dan
              Nov 23 '18 at 11:29
















            1














            You can do it like this:



            for inv in Invoice.objects.all():
            print(inv.custom.name)
            print(inv.custom.email)


            In template:



            {% for inv in invoices %}
            {{ inv.customer.name }}
            {% endfor %}


            And you need to send this information via context like:



            return render(request, 'template.html', { 'invoices': Invoice.objects.all() })


            You need to send the queryset from View to Template. You can use render to do that.



            If you are using a Class Based View, then try like this:



            class SomeListView(ListView):
            model = Invoice
            template = 'your_template.html'


            # template for list view
            {% for inv in object_list %}
            {{ inv.customer.name }}
            {% endfor %}


            See here for more details in ListView






            share|improve this answer



















            • 1




              Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
              – Dan
              Nov 23 '18 at 11:29














            1












            1








            1






            You can do it like this:



            for inv in Invoice.objects.all():
            print(inv.custom.name)
            print(inv.custom.email)


            In template:



            {% for inv in invoices %}
            {{ inv.customer.name }}
            {% endfor %}


            And you need to send this information via context like:



            return render(request, 'template.html', { 'invoices': Invoice.objects.all() })


            You need to send the queryset from View to Template. You can use render to do that.



            If you are using a Class Based View, then try like this:



            class SomeListView(ListView):
            model = Invoice
            template = 'your_template.html'


            # template for list view
            {% for inv in object_list %}
            {{ inv.customer.name }}
            {% endfor %}


            See here for more details in ListView






            share|improve this answer














            You can do it like this:



            for inv in Invoice.objects.all():
            print(inv.custom.name)
            print(inv.custom.email)


            In template:



            {% for inv in invoices %}
            {{ inv.customer.name }}
            {% endfor %}


            And you need to send this information via context like:



            return render(request, 'template.html', { 'invoices': Invoice.objects.all() })


            You need to send the queryset from View to Template. You can use render to do that.



            If you are using a Class Based View, then try like this:



            class SomeListView(ListView):
            model = Invoice
            template = 'your_template.html'


            # template for list view
            {% for inv in object_list %}
            {{ inv.customer.name }}
            {% endfor %}


            See here for more details in ListView







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 11:23

























            answered Nov 23 '18 at 11:14









            ruddraruddra

            12.2k32648




            12.2k32648








            • 1




              Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
              – Dan
              Nov 23 '18 at 11:29














            • 1




              Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
              – Dan
              Nov 23 '18 at 11:29








            1




            1




            Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
            – Dan
            Nov 23 '18 at 11:29




            Not using class based view, just the first view I came across in the documentation ha! Your other stuff worked but I approve @Vivek Signh's answer cause he said OneToOneField.
            – Dan
            Nov 23 '18 at 11:29


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445627%2fdjango-having-trouble-using-foreign-key-model%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            How to ignore python UserWarning in pytest?

            Alexandru Averescu