views:

41

answers:

3

In my django app, especially on the admin side, I do a few def's with my models:

def get_flora(self):
    return self.flora.all()

def targeted_flora(self):
    return u"%s" % (self.get_flora())

whereas flora is a ManyToManyField, however, sometimes ForeignKey fields are used also.

I do this to provide a utility 'get' function for the model, and then the second def is to provide django admin with a a friendlier field name to populate the tabular/list view.

Perhaps a two part question here: 1. Is this a good workflow/method for doing such things, and 2. The resultant string output in admin looks something like:

[<Species: pittosporum>, <Species: pinus radiata>]

Naturally enough, but how to make it look like:

pittosporum & pinus radiata

or, if there were three;

pittosporum, pinus radiata & erharta ercta

Super thanks!

A: 

Sounds like you want something like this:

def targeted_flora(self):
  names= [f.name for f in self.get_flora()] # or however you get a floras name
  if len(names) == 1:
    return names[0]
  else:
    return ', '.join(names[:-1]) + ' & ' + names[-1]
sth
Sweet! Good work and thank you... just needed to add a ':' after 'else'
Antonius Common
Right - I fixed it in the answer... :)
sth
A: 

Thanks again sth,

I wonder, I use this a lot, so I've attempted to make it a function that I can import.

Am I on the right track here?

def punctuated_object_list(objects, field):
    field_list = [f.field for f in objects]
    if len(field_list) > 0:
        if len(field_list) == 1:
            return field_list[0]
        else:
            return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
    else:
        return u''
Antonius Common
I probably should make another question here... but I need to wait 10 minutes!
Antonius Common
A: 

This works btw:

def punctuated_object_list(objects, field):
    if field:
        field_list = [getattr(f, field) for f in objects]
    else:
        field_list = [str(f) for f in objects]

    if len(field_list) > 0:
        if len(field_list) == 1:
            return field_list[0]
        else:
            return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
    else:
        return u''
Antonius Common