I have a Contact class that can have many Conversations. But each conversation can belong to a single Contact.
So its a One-To-Many relationship.
class Contact(models.Model):
first_name = models.CharField()
last_name = models.CharField()
class Conversation(models.Model):
contact = models.ForeignKey(Contact)
notes = models.TextField()
def __unicode__(self):
return self.notes
Now when I pass in the contacts to the template, I would like to have one field that shows the last conversation for the contact.
contacts= profile.company.contact_set.all()[:10]
calls = []
for c in contacts:
calls.append(max(c.conversation_set.all()))
And I pass them in like this:
vars = {'contacts' : contacts, 'calls': calls}
variables = RequestContext(request, vars)
return render_to_response('main_page.html', variables)
In the template I came up with this magic:
{% for idx, val in contacts %}
<tr>
<td>...
</td>
<td>
{% if calls %}
{{ calls.idx }}
{% endif %}</td>
</tr>
{% endfor %}
This doesn’t show anything for calls. But if I replaced calls.idx with calls.0 I get the first one displayed.
What am I doing wrong? Beside the fact that it could be done probably much easier than that. 🙂 I am open for better ways of doing it.
You can’t do this sort of indirect lookup in the template language –
calls.idxwill always refer to an attributeidxbelonging tocalls.However I think a better solution is to add the call value directly onto the contact object – don’t forget that in Python objects are dynamic, so you can annotate anything you like onto them.
As an aside, does that
maxreally work? I’m not sure what it would be doing the comparison based on. An alternative is to defineget_latest_byin your Conversation model, then you can avoid this loop altogether and just call{{ contact.conversation_set.get_latest }}in your template for each contact through the loop.(Note this will still be pretty inefficient, there are various ways of getting the whole set of max conversations in one go, but it will do for now.)