regroup, dictsort and ordering objects

270 views
Skip to first unread message

chrominance

unread,
Apr 22, 2007, 7:24:42 PM4/22/07
to Django users
I feel like maybe I've stretched the templating system to the breaking
point, but I'll ask anyways in case there's a solution.

I'm putting together templates for a calendar app, specifically one to
hold sports games/results. The first trick is I want to use the same
model for games already played and games in the future (DRY). The
second trick is I want to pass to my template a single list of
calendar items containing both games with scores and future games
without scores.

The model:

class SportsCalendarItem(models.Model):
sport = models.ForeignKey('SportType')
start_time = models.DateTimeField()
(...)

def is_played(self):
# determines whether a game has started or not, based on
start_time
(...)

class Meta:
ordering = ('start_time', 'sport')

The template (or at least the bits I think are relevant):

{% regroup items|dictsortreversed:"is_played" by is_played as times %}
{% for time in times %}
{% if time.grouper %}
<!-- time.grouper is actually the function
SportsCalendarItem.is_played(),-->
<!-- which returns True or False, hence the odd if tag--it doesn't
check for -->
<!-- the existence of time.grouper, it checks whether the value
time.grouper -->
<!-- holds is True or False.-->
<h3>Scoreboard</h3>
{% regroup time.list|dictsort:"sport" by sport as sports %}
{% for sport in sports %}
<p class="sidebar-calendar-date">{{ sport.grouper }}</p>
(...)

The basic idea is that I split the list of calendar items first by
is_played (so I can show scores for finished games and times for
upcoming games) and then by the sport itself (basketball, hockey,
etc.). This works great, except that for whatever reason, the order in
which the sports appear is random, when it should be alphabetically
sorted, or at least maintain a consistent sorting instead of changing
on every reload. I thought ordering the SportsCalendarItem by 'sport'
would do the trick, but apparently not; neither does the
dictsort|"sport".

Is there something else I'm missing, or is this one of those cases
where I'm trying to do way too much work with templates?

chrominance

unread,
Apr 26, 2007, 2:41:25 AM4/26/07
to Django users
Never mind, I didn't realize that a) dictsort doesn't work so well
when passed related objects, and b) dictsort does great when passed
FIELDS of related objects, say, SportType.name. Problem = solved!

Reply all
Reply to author
Forward
0 new messages