Get information from related object in generic list view
-
13-09-2019 - |
Question
So, I've been noodling about with Django's generic views, specifically the object_list
view. I have this in my urls.py
:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from diplomacy.engine.models import Game
game_info = {
"queryset": Game.objects.filter(state__in=('A', 'P')),
"template_object_name": "game",
}
urlpatterns = patterns('',
(r'^$', list_detail.object_list, game_info),
)
and this fairly rough template that it is going to:
{% block content %}
<table>
<tr>
<th>Name</th>
<th>Turn</th>
<th>Last Generated</th>
</tr>
{% for game in game_list %}
<tr>
<td>{{ game.name }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
What I'm looking for is the best idiomatic way of including in this view the unicode representation and generated
field (a DateTimeField
) from the most recent Turn
that points to the current Game
in the loop, based on the value of generated
. Turn.game
is the field that points to the Game
the turn belongs to (a ForeignKey
).
Update:
My Turn
model is as follows:
SEASON_CHOICES = (
('S', 'Spring'),
('SR', 'Spring Retreat'),
('F', 'Fall'),
('FR', 'Fall Retreat'),
('FB', 'Fall Build')
)
class Turn(models.Model):
game = models.ForeignKey(Game)
year = models.PositiveIntegerField()
season = models.CharField(max_length=2, choices=SEASON_CHOICES)
generated = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return "%s %s" % (self.season, self.year)
The Game
model has not appreciably changed from the way I specified it in this other question.
Solution
If Turn.game
points to the associated Game
object, then {{game.turn_set.all}}
should return the set of Turn
objects for that game.
You may need to add a Meta class to the Turn
model to order from newest to oldest.
Class Meta:
ordering = ['-generated']
Then, {{game.turn_set.all.0}}
should return the unicode representation for the newest turn for that game, and {{game.turn_set.all.0.generated}}
will return the associated datetime
object.
Note: This is untested code.