简体   繁体   中英

Django - Having trouble using foreign key model

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'?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM