Internal APIs — django-tables2 1.0.4 documentation

# Internal APIs

The items documented here are internal and subject to change. It exists here for convenience.

## `BoundColumns`

class `django_tables2.columns.` `BoundColumns`(table)

  Container for spawning `BoundColumn` objects.

  This is bound to a table and provides its `Table.columns` property. It provides access to those columns in different ways (iterator, item-based, filtered and unfiltered etc), stuff that would not be possible with a simple iterator in the table class.

  A `BoundColumns` object is a container for holding `BoundColumn` objects. It provides methods that make accessing columns easier than if they were stored in a `list` or `dict`. `Columns` has a similar API to a `dict` (it actually uses a `OrderedDict` interally).

  At the moment you’ll only come across this class when you access a `Table.columns` property.

  Parameters: | table (`Table` object) – the table containing the columns

  `__contains__`(item)

    Check if a column is contained within a `Columns` object.

    item can either be a `BoundColumn` object, or the name of a column.

  `__getitem__`(index)

    Retrieve a specific `BoundColumn` object.

    index can either be 0-indexed or the name of a column

        columns['speed']  # returns a bound column with name 'speed'
        columns[0]        # returns the first column

  `__iter__`()

    Convenience API, alias of `itervisible`.

  `__len__`()

    Return how many `BoundColumn` objects are contained (and visible).

  `__weakref__`

    list of weak references to the object (if defined)

  `iterall`()

    Return an iterator that exposes all `BoundColumn` objects, regardless of visiblity or sortability.

  `iteritems`()

    Return an iterator of `(name, column)` pairs (where `column` is a `BoundColumn`).

    This method is the mechanism for retrieving columns that takes into consideration all of the ordering and filtering modifiers that a table supports (e.g. `exclude` and `sequence`).

  `iterorderable`()

    Same as `BoundColumns.all` but only returns orderable columns.

    This is useful in templates, where iterating over the full set and checking `{% if column.sortable %}` can be problematic in conjunction with e.g. `{{ forloop.last }}` (the last column might not be the actual last that is rendered).

  `itervisible`()

    Same as `iterorderable` but only returns visible `BoundColumn` objects.

    This is geared towards table rendering.

## `BoundColumn`

class `django_tables2.columns.` `BoundColumn`(table, column, name)

  A run-time version of `Column`. The difference between `BoundColumn` and `Column`, is that `BoundColumn` objects include the relationship between a `Column` and a `Table`. In practice, this means that a `BoundColumn` knows the “variable name” given to the `Column` when it was declared on the `Table`.

  For convenience, all `Column` properties are available from thisclass.

  - > Parameters: | table (`Table` object) – the table in which this column exists column (`Column` object) – the type of column name (string object) – the variable name of the column used to when defining the `Table`. In this example the name is `age`:
    >     class SimpleTable(tables.Table):
    >         age = tables.Column()

  `__weakref__`

    list of weak references to the object (if defined)

  `accessor`

    Returns the string used to access data for this column out of the data source.

  `attrs`

    Proxy to `Column.attrs` but injects some values of our own.

    A `th` and `td` are guaranteed to be defined (irrespective of what’s actually defined in the column attrs. This makes writing templates easier.

  `default`

    Returns the default value for this column.

  `header`

    The value that should be used in the header cell for this column.

  `localize`

    Returns `True`, `False` or `None` as described in `Column.localize`

  `order_by`

    Returns an `OrderByTuple` of appropriately prefixed data source keys used to sort this column.

    See `order_by_alias` for details.

  `order_by_alias`

    Returns an `OrderBy` describing the current state of ordering for this column.

    The following attempts to explain the difference between `order_by` and `order_by_alias`.

    `order_by_alias` returns and `OrderBy` instance that’s based on the name of the column, rather than the keys used to order the table data. Understanding the difference is essential.

    Having an alias and a keys version is necessary because an N-tuple (of data source keys) can be used by the column to order the data, and it’s ambiguous when mapping from N-tuple to column (since multiple columns could use the same N-tuple).

    The solution is to use order by aliases (which are really just prefixed column names) that describe the ordering state of the column, rather than the specific keys in the data source should be ordered.

    e.g.:

        >>> class SimpleTable(tables.Table):
        ...     name = tables.Column(order_by=("firstname", "last_name"))
        ...
        >>> table = SimpleTable([], order_by=("-name", ))
        >>> table.columns["name"].order_by_alias
        "-name"
        >>> table.columns["name"].order_by
        ("-first_name", "-last_name")

    The `OrderBy` returned has been patched to include an extra attribute `next`, which returns a version of the alias that would be transitioned to if the user toggles sorting on this column, e.g.:

        not sorted -> ascending
        ascending  -> descending
        descending -> ascending

    This is useful otherwise in templates you’d need something like:

    > {% if column.is_ordered %} {% querystring table.prefixed_order_by_field=column.order_by_alias.opposite %} {% else %} {% querystring table.prefixed_order_by_field=column.order_by_alias %} {% endif %}

  `orderable`

    Return a `bool` depending on whether this column supports ordering.

  `sortable`

    deprecated – use `orderable` instead.

  `verbose_name`

    Return the verbose name for this column, or fallback to the titlised column name.

    If the table is using queryset data, then use the corresponding model field’s `verbose_name`. If it’s traversing a relationship, then get the last field in the accessor (i.e. stop when the relationship turns from ORM relationships to object attributes [e.g. person.upper should stop at person]).

  `visible`

    Returns a `bool` depending on whether this column is visible.

## `BoundRows`

class `django_tables2.rows.` `BoundRows`(data, table)

  Container for spawning `BoundRow` objects.

  Parameters: | data – iterable of records table – the table in which the rows exist

  This is used for `Table.rows`.

  `__getitem__`(key)

    Slicing returns a new `BoundRows` instance, indexing returns a single `BoundRow` instance.

  `__weakref__`

    list of weak references to the object (if defined)

## `BoundRow`

class `django_tables2.rows.` `BoundRow`(record, table)

  Represents a specific row in a table.

  `BoundRow` objects are a container that make it easy to access the final ‘rendered’ values for cells in a row. You can simply iterate over a `BoundRow` object and it will take care to return values rendered using the correct method (e.g. Table.render_FOO() methods)

  To access the rendered value of each cell in a row, just iterate over it:

      >>> import django_tables2 as tables
      >>> class SimpleTable(tables.Table):
      ...     a = tables.Column()
      ...     b = tables.CheckBoxColumn(attrs={'name': 'my_chkbox'})
      ...
      >>> table = SimpleTable([{'a': 1, 'b': 2}])
      >>> row = table.rows[0]  # we only have one row, so let's use it
      >>> for cell in row:
      ...     print cell
      ...
      1
      <input type="checkbox" name="my_chkbox" value="2" />

  Alternatively you can treat it like a list and use indexing to retrieve a specific cell. It should be noted that this will raise an IndexError on failure.

      >>> row[0]
      1
      >>> row[1]
      u'<input type="checkbox" name="my_chkbox" value="2" />'
      >>> row[2]
      ...
      IndexError: list index out of range

  Finally you can also treat it like a dictionary and use column names as the keys. This will raise KeyError on failure (unlike the above indexing using integers).

      >>> row['a']
      1
      >>> row['b']
      u'<input type="checkbox" name="my_chkbox" value="2" />'
      >>> row['c']
      ...
      KeyError: 'c'

  Parameters: | table – is the `Table` in which this row exists. record – a single record from the table data that is used to populate the row. A record could be a `Model` object, a `dict`, or something else.

  `__contains__`(item)

    Check by both row object and column name.

  `__getitem__`(name)

    Returns the final rendered value for a cell in the row, given the name of a column.

  `__iter__`()

    Iterate over the rendered values for cells in the row.

    Under the hood this method just makes a call to `BoundRow.__getitem__` for each cell.

  `__weakref__`

    list of weak references to the object (if defined)

  `items`()

    Returns iterator yielding `(bound_column, cell)` pairs.

    cell is `row[name]` – the rendered unicode value that should be `rendered within ``<td>`.

  `record`

    The data record from the data source which is used to populate this row with data.

  `table`

    The associated `Table` object.

## `TableData`

class `django_tables2.tables.` `TableData`(data, table)

  Exposes a consistent API for table data.

  Parameters: | data (`QuerySet` or `list` of `dict`) – iterable containing data for each row table – `Table` object

  `__getitem__`(key)

    Slicing returns a new `TableData` instance, indexing returns a single record.

  `__iter__`()

    for ... in ... default to using this. There’s a bug in Django 1.3 with indexing into querysets, so this side-steps that problem (as well as just being a better way to iterate).

  `__weakref__`

    list of weak references to the object (if defined)

  `order_by`(aliases)

    Order the data based on order by aliases (prefixed column names) in the table.

    Parameters: | aliases (`OrderByTuple`) – optionally prefixed names of columns (‘-‘ indicates descending order) in order of significance with regard to data ordering.

  `ordering`

    Returns the list of order by aliases that are enforcing ordering on the data.

    If the data is unordered, an empty sequence is returned. If the ordering can not be determined, `None` is returned.

    This works by inspecting the actual underlying data. As such it’s only supported for querysets.