Skip to content
Advertisement

get more than two foreign keys from another django table and perform calculations on them

In the Django app, I have created two tables. Product Invoice

I have one table called Product which contains product name and product price columns are given.

Then, I have a second table named Invoice which contains a product name(foreign key), product price(foreign key), discount, and total.

My concern is how can I import both the values from the Product table i.e. product name and product price and perform calculations on them. The structure is given below:

myapp -> PRODUCT: *Product Name *Product Id *Product Price

    INVOICE:
        *Product Name (foreign key)
        *Product Id (foreign key)
        *Product Price (foreign key)
        *Discount
        *Total = Product Price - Discount

how can I import values and perform further calculations?

Advertisement

Answer

The best way is to use the product as a foreign key inside the Invoice. You do not need all fields to be mentioned inside Invoice. If you want to access them you can do so by invoice.product.name, price or id ( using invoice instance). Let me give you an overview of how it will look like

class Product(db.Model):
"""
Product details
"""

class Invoice(db.Model)
"""
invoice details 
"""

product = db.ForeignKey(Product, related_name= "invoices", **other_fields)

Now for example if you need a name, id, or any other field from the product for a specific invoice. Then first you have to query the invoice and get an instance from the invoice table and then gets related product details

Code example:

invoice = Invoice.objects.filter(**filter_conditions).first()

Now do further logic on the product using below format

invoice.product.id
invoice.product.name
invoice.product.price

and any other logic that needs to be done here it goes.

That is how you can achieve what you want to achieve here.

Advertisement