Work with Many-To-One Relation Ship

Hi everyone !

I would like to print out the number of orders that were created for a customer, the models hereunder were simplified for this topic :

    class CustomerModel(models.Model):
        customer_first_name = models.CharField(max_length=40, default="")
        customer_surname = models.CharField(max_length=40, default="")

    def __str__(self):
        return self.customer_first_name

    class OrderModel(models.Model):
        order_date = models.DateTimeField(auto_now_add=True)
        order_customer = models.ForeignKey(CustomerModel, related_name="order_customer", default=None, on_delete=models.CASCADE, blank=True)

As “order_customer” is a ForeignKey related to the CustomerModel, how can I print out the number of orders through a customer for loop ? :

            <table>
                <thead>
                    <tr>
                        <td></td>
                        <td>Customers</td>
                        <td>Orders</td>
                    </tr>
                </thead>
                <tbody>
                    {% for customer in customerModel %}
                    <tr>
                        <td>
                            <button type="button" class="button_style"><a href="#">View</a></button>
                        </td>
                        <td>{{ customer.customer_first_name }} {{ customer.customer_surname }}</td>
                        <td>{{ customer.order_customer }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>

Thanks in advance for your help

I’m not sure I’m understanding what you’re trying to do here.

Are you saying you want to add a column in your table to display something like an index number?
If so, see the forloop variables in the Builtin template tags and filters page.

Hi @KenWhitesell,

I’m trying to print every client in my database in the “index.html” page. For each client I want to print their name and then the total number of orders related to them.

For example Mr X has 3 orders total (3 Order objects from OrderModel were created and linked to Mr X)

Ah, ok.

So your related name is order_customer, which means that in your template you could use {{ customer.order_customer_set.count }}