[Fixed]-How to sum all integer properties from ForeignKey objects in django template?

1👍

There are several ways.

1 – product.get_total_order()
If you’ll reuse this somewhere, you can add a method in the model:

class Product(models.Model):
    ...

    def get_total_order(self):
         return ...

and display it in the template:

{{ product.get_total_order }}

2.In the view
If you never reuse that information:

def your_view(request, ...):
     return render(request, template_name...html, {'total_order': xxx})

Template:

{{ total_order }}

3.As a template tag
If you’ll re-use it, but you don’t like the first option (to keep the model light), you could add a filter tag:

{{ product|product_total_order }}

Notes / comments:

  • please post the code you’ve tried if you can’t figure it out
  • Orderitem => OrderItem
  • I highly recommend to add related_name in your foreign keys

Leave a comment