[Answered ]-Nested object listing with conditions

2👍

Django helps you create most common queries without needing to resort to raw SQL. Actually figuring out how to translate what you want to what Django needs you to write down can be tricky. The most helpful thing to remember when trying to make a query: start the query with what you want.

If it is Orders that you want, you should query for Orders (instead of OrderingDay objects like you’re doing in your example).

So you want a user’s orders? Something like Order.filter(user=self.request.user).

Ah, but you want those orders grouped by day? Easiest is to first simplify the query output by adding a .values() to it: “Order.filter(user=self.request.user).values(‘date’, ‘item’)`. This returns a simple list of dicts:

[{'date': 'date 1',
  'item': 'hamburgers'},
 {...},
 {...}]  

Then you can use the ‘regroup’ template tag in your template. Regroup by 'date' in your case.

Alternatively, you can do it in code. To your CurrentOrdersListingView class, add a items_per_day() method with something like this:

def items_per_day(self):
    ... your custom grouping code ...
    ... return ['date 1': [item1, item2, item3],
                'date 2': [item2],
                ...

And simply call that method in your template:

{% for date, items in view.items_per_day %}
  <h2>{{ date }}</h2>
  ....
 {% endfor %}

(Methods on a view class are available as view.method_name in the template automatically).


Here’s the solution that was used in the end:

You can select all Orders using:

def get_queryset(self):
    return OM.Order.objects.order_by('date__date')\
           .filter(user=self.request.user)

And then use regroup (it is able to work with model objects perfectly) with sort:

{% regroup ordering_days|dictsort:"date.date" by date as ordering_items %}
{% for ordering_day in ordering_items %}
    <h3>{{ ordering_day.grouper.date|date:'l' }}</h3>
    {% for oi in ordering_day.list %}
        {{ oi.item.name }}
    {% endfor %}
{% endfor %}

Leave a comment