AverageJoe9000
AverageJoe9000

Reputation: 338

How to get all objects based on date in Django

I have 3 simple models in my application:

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.IntegerField(default=0)

class Order (models.Model):
    date = models.DateField(blank=True)

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True )
    product = models.ManyToManyField(Product)
    quantity = models.PositiveIntegerField(default=0)

I have many orders with the same date, like this:

1. 2017-11-09 | Apples  | 5$
2. 2017-11-09 | Bananas | 2$
3. 2017-11-09 | Pears   | 3$

As you can see, there is actually one order (based on the date) with 3 different products. How can I get that single order with all of its products and prices? So the end result would be something like this:

2017-11-09 | Apples  | 5$
           | Bananas | 2$
           | Pears   | 3$

I'm using sqllite3

Upvotes: 0

Views: 254

Answers (2)

aleks.chehov
aleks.chehov

Reputation: 1

You must watch template template tags {% regroup %}

Upvotes: 0

user8060120
user8060120

Reputation:

in the django template you can try it:

<table>
    {% for order in orders %}
        {% for item in order.orderitem_set.all %}
        <tr>
            <td>{% if forloop.first %}{{ order.date }}{% endif %}</td>
            <td>{{ item.product.name }}</td>
            <td>{{ item.quantity }}</td>
        </tr>
        {% endfor %}
    {% endfor %}
</table>

in views function add:

return render (request, 'index.html', context={'orders': Order.objects.all()})

Upvotes: 2

Related Questions