Pages

Monday, August 20, 2007

Defining more complex names with Django

The easiest way to define self for a Model:

def __str__(self):
  return self.name

Name is a field in the Model. self.name takes the value for 'name' and uses it as the default string representation for that row.

You can also user more complex strings to define self. In this example, 'country' is another ForeignKeyField column in the Model, and 'abbr_2' is a column in the Country model. Dot notation lets you travel across Models:

def __str__(self):
  return '%s, %s' % (self.name, self.country.abbr_2)

I think you can also uses custom managers to get even fancier, but I can't figure that out.

No comments: