bash-
bash-

Reputation: 6314

Cannot access a value in Django

I'm trying to access bc_product.eng_name in the following code but it's not working. The foreign key of the bc_product table is in bc_invoice_product table. Can someone point me in the right direction?

View

def invoice_pdf(request, inv_no):

    inv = BC_Invoice.objects.select_related().get(invoice_no=inv_no)
    return render_to_pdf('bc_invoice_pdf.html', {'pagesize': 'A4',
                                                  'inv': inv})

Template

{% for item in inv.bc_invoice_product_set.all %}
    <tr>
        <td align=center>{{ item.unit_quantity }}</td>
        <td align=center>{{ item.bc_product.eng_name }}</td>
        <td align=center>{{ item.unit_price }}</td>
        <td align=center>{{ item.unit_amount }}</td>
    </tr>
{% endfor %}

UPDATE:

Model

class BC_Product(models.Model):
    ............
    eng_name = models.CharField(max_length=200)

class BC_Invoice(models.Model):
    ............    
    product = models.ManyToManyField(BC_Product, through='BC_Invoice_Product')

class BC_Invoice_Product(models.Model):
    ............
    invoice = models.ForeignKey(BC_Invoice)
    product = models.ForeignKey(BC_Product)

Upvotes: 0

Views: 70

Answers (2)

bmihelac
bmihelac

Reputation: 6323

It looks to me that inv.bc_invoice_product_set.all returns BC_Invoice_Product models and in this case you should use {{ item.product.eng_name }}.

From your models it is visible that foreign key relationship fied toBC_Product in BC_Invoice_Product is product and not bc_product.

Also, convention is to have ForeignKey field named as a model name, lowercased - that would probably make it much easier to follow relationships.

Upvotes: 1

Koobz
Koobz

Reputation: 6938

Are you able to look the value up outside the view? Fire of the development server, stick:

import pdb; pdb.set_trace()

In after inv = ...

And explore the query API a bit in the console to see if it matches your expectations. What you've got should work.

Upvotes: 0

Related Questions