I've just come up with what looks like a rather ugly solution for
certain problem, and I'm hoping someone might have comments for
improvement.

I've got a Book model, with a M2M relationship with an Author model,
ie possibly several authors per book. In my book template, I wanted to
use a for loop to produce output like so:

One author: "This book is by John Doe."
Two authors: "This book is by John Doe and Jane Doe."
Three or more authors: "This book is by John Doe, Jane Doe, Eustace
Tilley, [more] and Fred"

After much screwing around with for loops in the view and in the
template, I eventually decided to construct a mini-template using a
function in the views.py file. It looks like this (item is the book
object, and it has an author field):

======
def makeAuthChunk(item):
    authCount = item.author.count()
    if authCount == 1:
        auth = item.author.all()[0]
        authChunk = """<a href="%s">%s</a>""" %
(auth.get_absolute_url(), auth)
    elif authCount == 2:
        auth1 = item.author.all()[0]
        auth2 = item.author.all()[1]
        authChunk = """<a href="%s">%s</a> and <a href="%s">%s</a>"""
% (auth1.get_absolute_url(), auth1, auth2.get_absolute_url(), auth2)
    else: # ie, more than 2 authors
        firstAuth = item.author.order_by("id")[0]
        lastAuth = item.author.order_by("-id")[0]
        otherAuth =
item.author.all().exclude(pk=firstAuth.pk).exclude( pk=lastAuth.pk)
        authChunk = """<a href="%s">%s</a>""" %
(firstAuth.get_absolute_url(), firstAuth)
        for auth in otherAuth:
            authChunk += """, <a href="%s">%s</a>""" %
(auth.get_absolute_url(), auth)
        authChunk += """ and <a href="%s">%s</a>""" %
(lastAuth.get_absolute_url(), lastAuth)
    return authChunk

=====

Hope the formatting survives. I have two questions:

1. Is there really no easier way to do this?
2. I'm up against the negative indexing problem in getting the last
author, and while the negative order_by seems okay, given that id is
unique, I'm wondering if there is a better way to accomplish that.

Any suggestions or alternative solutions would be much appreciated...

Thanks,
Eric
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to